我正在尝试完成以下任务...

我得到了一个Pandas数据框,其中包含许多条目,并用DatetimeIndex进行了索引,看起来有点像这样:

bro_df.info()

<class 'bat.log_to_dataframe.LogToDataFrame'>
DatetimeIndex: 3596641 entries, 2017-12-14 13:52:01.633070 to 2018-01-03 09:59:53.108566
Data columns (total 20 columns):
conn_state        object
duration          timedelta64[ns]
history           object
id.orig_h         object
id.orig_p         int64
id.resp_h         object
id.resp_p         int64
local_orig        bool
local_resp        bool
missed_bytes      int64
orig_bytes        int64
orig_ip_bytes     int64
orig_pkts         int64
proto             object
resp_bytes        int64
resp_ip_bytes     int64
resp_pkts         int64
service           object
tunnel_parents    object
uid               object
dtypes: bool(2), int64(9), object(8), timedelta64[ns](1)
memory usage: 528.2+ MB

我感兴趣的是获取此数据的一部分,该数据采用本例中的最后一个条目,即2018-01-03 09:59:53.108566',然后从中减去一个小时。这应该给我最后几个小时的输入时间。

到目前为止,我已经尝试做以下事情:
last_entry = bro_df.index[-1:]
first_entry = last_entry - pd.Timedelta('1 hour')

如下所示,这给了我什么,我看起来像是相当正确的值:
print(first_entry)
print(last_entry)

DatetimeIndex(['2018-01-03 08:59:53.108566'], dtype='datetime64[ns]', name='ts', freq=None)
DatetimeIndex(['2018-01-03 09:59:53.108566'], dtype='datetime64[ns]', name='ts', freq=None)

可悲的是,这也是我卡住的地方。我已经尝试了bro_df.loc和bro_df.iloc的各种操作,等等,但是我得到的只是数据类型的错误不同,而不是索引等错误。这使我认为我可能需要将first_entry,last_entry变量转换为另一种类型?

或像往常一样,我可能完全是在树错误的树上。

任何帮助或指导将不胜感激。

干杯,迈克

最佳答案

看来您需要通过为[0]编制索引来创建标量,并通过loc进行选择:

df = bro_df.loc[first_entry[0]: last_entry[0]]

或按exact indexing选择:
df = bro_df[first_entry[0]: last_entry[0]]

样本:
rng = pd.date_range('2017-04-03', periods=10, freq='2H 24T')
bro_df = pd.DataFrame({'a': range(10)}, index=rng)
print (bro_df)
                     a
2017-04-03 00:00:00  0
2017-04-03 02:24:00  1
2017-04-03 04:48:00  2
2017-04-03 07:12:00  3
2017-04-03 09:36:00  4
2017-04-03 12:00:00  5
2017-04-03 14:24:00  6
2017-04-03 16:48:00  7
2017-04-03 19:12:00  8
2017-04-03 21:36:00  9
last_entry = bro_df.index[-1:]
first_entry = last_entry - pd.Timedelta('3 hour')
print (last_entry)
DatetimeIndex(['2017-04-03 21:36:00'], dtype='datetime64[ns]', freq='144T')

print (first_entry)
DatetimeIndex(['2017-04-03 18:36:00'], dtype='datetime64[ns]', freq=None)

print (last_entry[0])
2017-04-03 21:36:00

print (first_entry[0])
2017-04-03 18:36:00

df = bro_df.loc[first_entry[0]: last_entry[0]]
print (df)
                     a
2017-04-03 19:12:00  8
2017-04-03 21:36:00  9

df1 = bro_df[first_entry[0]: last_entry[0]]
print (df1)
                     a
2017-04-03 19:12:00  8
2017-04-03 21:36:00  9

关于pandas - 根据时间间隔对带有DatetimeIndex的Pandas数据框进行切片,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48110421/

10-09 06:57
查看更多