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)



原作者:
...