others - python - 如何使用Pandas的timedelta选择n个最后一个值?

我有一个Pandas series ,索引为时间戳,值为浮点数


pd.Series(


 data=[150.0, 151.0, ...],


 index=[


 datetime.datetime(2020, 1, 24, 15, 53, 54, 532325, tzinfo=None, fold=0),


 datetime.datetime(2020, 1, 24, 16, 1, 7, 896288, tzinfo=None, fold=0),


 ...]


)



结果:


2020-01-24T15:53:54.532325 150.0


2020-01-24T16:01:07.896288 151.0


2020-01-24T16:01:10.862610 152.0


2020-01-24T16:01:13.407573 149.0


2020-01-24T16:33:59.985246 148.0


2020-01-24T16:34:06.411970 150.0



我如何通过timedelta w.r.t选择n个最后一个值及其相应的索引。


2020-01-24T16:33:59.985246 148.0


2020-01-24T16:34:06.411970 150.0



时间: 原作者:

Inial df


print(df)


# date value


#0 2020-01-24 15:53:54.532325 150.0


#1 2020-01-24 16:01:07.896288 151.0


#2 2020-01-24 16:01:10.862610 152.0


#3 2020-01-24 16:01:13.407573 149.0


#4 2020-01-24 16:33:59.985246 148.0


#5 2020-01-24 16:34:06.411970 150.0



如果未排序DataFrame.sort_values,就可以使用DataFrame.tail或select with DataFrame.iloc


n = 2 


df_2_recent = df.sort_values('date').tail(n)


#df_2_recent = df.sort_values('date')[-n:]


#df_2_recent = df.sort_values('date').iloc[-n:,:]



# date value


#4 2020-01-24 16:33:59.985246 148.0


#5 2020-01-24 16:34:06.411970 150.0



如果需要选择列值:


df.sort_values('date').tail(2)['value']



如果timestamp是索引


df.sort_index().tail(2)



原作者:
...