如何将 pandas 时间序列限制为最后 n 秒?

How can I limit a pandas time series to the n last seconds?

我有一个pandas时间序列

time_series = pd.Series(data=[3,4,5], index=pd.DatetimeIndex(['2020-07-07 00:06:00.283', '2020-07-07 00:06:02.542', '2020-07-07 00:06:02.829']), name='I'))

ISO 格式 datetime 时间戳为 index。如何获得与最后 n 秒(例如 1 秒)对应的时间序列子集?

您可以获取索引的最后一个值并从中减去自定义时间步长,然后select具有较大值的所有索引

n_sec = 1
time_series.index = pd.to_datetime(time_series.index, format="%Y-%m-%d %H:%M:%S")
first_value = time_series.index.max() - pd.to_timedelta(n_sec, unit='s')

应该产生

> print(time_series[first_value:])
2020-07-07 00:06:02.542    4
2020-07-07 00:06:02.829    5
Name: I, dtype: int64

使用 datetime.timedelta 的单个衬里将是

import pandas as pd
import datetime

time_series = pd.Series(data=[3,4,5], index=pd.DatetimeIndex(['2020-07-07 00:06:00.283', '2020-07-07 00:06:02.542', '2020-07-07 00:06:02.829']), name='I')

time_series.loc[time_series.index >= max(time_series.index) - datetime.timedelta(seconds=1)]
# 2020-07-07 00:06:02.542    4
# 2020-07-07 00:06:02.829    5
# Name: I, dtype: int64