Python 使用DatetimeIndex切片数据帧

Python 使用DatetimeIndex切片数据帧,python,pandas,datetime,dataframe,Python,Pandas,Datetime,Dataframe,我有一个按颜色排序的数据帧,让我们以这个为例: import pandas as pd import numpy as np dates = pd.date_range('2011-04-01 00:00', periods=300, freq='min') random_dates = pd.to_datetime(np.random.choice(dates, size=20,replace=False)).sort_values() numbers = np.random.unifo

我有一个按颜色排序的数据帧,让我们以这个为例:

import pandas as pd
import numpy as np

dates = pd.date_range('2011-04-01 00:00', periods=300, freq='min')

random_dates = pd.to_datetime(np.random.choice(dates, size=20,replace=False)).sort_values()

numbers = np.random.uniform(low=-1, high=1, size=(20,))

df = pd.DataFrame(index=random_dates, data=numbers)
如果我们打印它:

...
2011-04-01 02:03:00 -0.404476
2011-04-01 02:38:00  0.205260
2011-04-01 02:44:00  0.111812
2011-04-01 03:10:00 -0.071028
2011-04-01 03:55:00 -0.203999
如何获取数据帧时间索引最后N分钟/小时内的行


例如,如果我想要最后一个小时(从最后一行开始计算),我会从上面的示例中得到最后两行。

假设您的数据帧是按索引排序的,您可以使用
pd.Timedelta
从最终索引项中减去任意时间量

然后根据
df.index
过滤数据帧

lower_range = df.index[-1] - pd.Timedelta(hours=1)

df = df.loc[df.index > lower_range]

print(df)

#                             0
# 2011-04-01 04:10:00 -0.116102
# 2011-04-01 04:59:00  0.364772

假设您的数据帧是按索引排序的,您可以使用
pd.Timedelta
从最终索引项中减去任意时间量

然后根据
df.index
过滤数据帧

lower_range = df.index[-1] - pd.Timedelta(hours=1)

df = df.loc[df.index > lower_range]

print(df)

#                             0
# 2011-04-01 04:10:00 -0.116102
# 2011-04-01 04:59:00  0.364772