【问题标题】:Pandas: Rolling statistics with business hoursPandas:营业时间滚动统计
【发布时间】:2021-10-05 07:25:10
【问题描述】:

我用时间戳索引了下表。

数据是在上午 8 点到晚上 11 点的工作时间,但会持续多天

当我执行像平均值这样的滚动统计并将时间段指定为 24 小时时,窗口从 1 月 5 日重叠到 1 月 4 日。

具体来说,我想知道如何有效地执行滚动周期以仅包括窗口中的当天。

我目前低效的方法是创建一个自定义函数,为每个滚动计算选择有效的时间戳索引,但这非常慢。

def mean(x):
    x = x[(x.index.hour >= 8) & (x.index.hour <= 23)]
    return 100.0 * (sum(x) / (len(x)))

Index Value Normal Desired
2021-01-04 08:35:15 0 0 0
2021-01-04 10:35:45 0 0 0
2021-01-04 16:35:30 1 0.333 0.333
2021-01-04 21:35:00 1 0.5 0.5
2021-01-05 08:15:00 1 0.6 1.0
2021-01-05 08:35:15 0 0.5 0.5
2021-01-05 12:35:42 0 0.428 0.333
2021-01-05 14:35:24 1 0.5 0.5
2021-01-04 20:35:23 0 0.444 0.4

【问题讨论】:

    标签: python pandas timestamp average rolling-computation


    【解决方案1】:

    您可以通过将 groupby 操作与窗口操作链接起来来获得所需的结果。根据documentation,这将“首先按指定键对数据进行分组,然后按组执行窗口操作”。

    In [711]: df.groupby(lambda x: x.date()).rolling('1D').mean().reset_index(0, drop=True)
    Out[711]:
                            Value
    2021-01-04 08:35:15  0.000000
    2021-01-04 10:35:45  0.000000
    2021-01-04 16:35:30  0.333333
    2021-01-04 21:35:00  0.500000
    2021-01-05 08:15:00  1.000000
    2021-01-05 08:35:15  0.500000
    2021-01-05 12:35:42  0.333333
    2021-01-05 14:35:24  0.500000
    2021-01-05 20:35:23  0.400000
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-11
      • 2011-11-08
      • 2015-03-07
      • 1970-01-01
      • 2018-01-21
      • 2018-11-07
      • 1970-01-01
      • 2015-04-11
      相关资源
      最近更新 更多