【问题标题】:How can I limit a pandas time series to the n last seconds?如何将熊猫时间序列限制为最后几秒?
【发布时间】:2020-10-30 03:21:29
【问题描述】:

我有一个熊猫时间序列

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 秒)相对应的时间序列子集?

【问题讨论】:

  • 本系列的预期输出是什么?
  • W.r.t.上面的示例和 1 秒的时间增量我希望数据对应于 '2020-07-07 00:06:02.542', '2020-07-07 00:06:02.829'

标签: python pandas datetime time-series series


【解决方案1】:

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

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

【讨论】:

  • 嗯,我得到TypeError: Cannot convert input [DatetimeIndex(['2020-07-07 00:12:40.200000+00:00', '2020-07-07 00:12:39.200000+00:00', '2020-07-07 00:12:37.200000+00:00'], dtype='datetime64[ns, UTC]', freq=None)] of type <class 'pandas.core.indexes.datetimes.DatetimeIndex'> to Timestamp
  • 您的代码有效。不过我更喜欢@Ric_S 的单行解决方案。
【解决方案2】:

使用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

【讨论】:

    猜你喜欢
    • 2012-10-16
    • 1970-01-01
    • 2019-03-03
    • 1970-01-01
    • 2014-08-28
    • 2023-03-31
    • 2016-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多