【问题标题】:How to select the last values from a pandas series using timedelta?如何使用 timedelta 从熊猫系列中选择最后一个值?
【发布时间】:2020-05-10 23:20:47
【问题描述】:

我有一个 pandas 系列,其中时间戳作为索引,浮点数作为值

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 选择最后一个值及其对应的索引。以秒为单位的最新 timedelta 值?例如给定的系列和 2 秒的时间增量我希望是系列的子集

2020-01-24T16:33:59.985246    148.0
2020-01-24T16:34:06.411970    150.0

这应该等同于我通过indexing by time 使用timestamped_intensity['2020-01-24T16:33:59.9852462':'2020-01-24T16:34:06.411970'] 得到的。

【问题讨论】:

  • 不,他需要最后 2 条记录 ;-)

标签: python pandas time-series series


【解决方案1】:

更新

按元素 Series.sort_index

s.sort_index().tail(2)

#date
#2020-01-24 16:33:59.985246    148.0
#2020-01-24 16:34:06.411970    150.0
#Name: value, dtype: float64

以秒为单位

我们计算索引时的时间差和索引时的累积和和semnor那2

n = 2
s[s.sort_index(ascending = False)
   .index
   .to_series()
   .diff().abs()
   .dt.total_seconds()
   .cumsum()
   .fillna(0)
   .lt(n)]

【讨论】:

  • 或(更灵活)....iloc[-2:, :] 还可以考虑制作副本以避免意外。所以,.copy() 在结果之后。
  • 我使用的是熊猫系列,没有熊猫数据框。
  • 我想按 timedelta 索引,而不是 # 个元素...我试图改进这个问题。
  • 按秒检查
  • 有效,但我的解决方案更灵活,因为它也可以以天、微秒等为单位定义时间增量。
【解决方案2】:

不好,但对我有用:

timedelta_in_seconds = 2
most_recent_timestamp = timestamped_intensity.sort_index().index[-1]
timestamped_intensity[most_recent_timestamp - datetime.timedelta(seconds=timedelta_in_seconds):most_recent_timestamp]

【讨论】:

  • 你不需要tail,只需要most_recent_timestamp = timestamped_intensity.sort_index().index[-1]
  • 不,我想我需要它。否则我得到的不是我所期望的。
  • 我确定,检查一下
  • most_recent_timestamp = timestamped_intensity.sort_index().index[-1]
  • sort_index() 很尴尬...如果索引没有排序,那么索引将不起作用,因为它返回一系列行,所以它取决于它是否排序。所以我只是将它改写为“假设索引已排序......”或者“首先确保您的索引已排序......”然后继续回答。还有,右边不需要间隔,timestamped_intensity[most_recent_timestamp - pd.to_timedelta('2s'):]就够了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-25
  • 2016-12-17
  • 2021-11-30
  • 2021-12-05
  • 2020-05-01
  • 1970-01-01
相关资源
最近更新 更多