【问题标题】:Pandas: rolling sum using precedent rows within timeframe, with time not the index熊猫:在时间范围内使用先例行滚动总和,时间不是索引
【发布时间】:2020-03-19 06:02:21
【问题描述】:

假设我有以下数据框:

data = {'measure_id': ['0', '1', '2', '3', '4'],
        'measure_time': ['2019-11-22 22:30:08.559000', '2019-11-22 22:36:09.149000', '2019-11-22 22:36:09.149000', '2019-11-22 22:40:09.261000', '2019-11-22 22:46:10.011000'],
        'pressure': [10, 9, 3, 11, 12]}
df = pd.DataFrame(data, columns=['measure_id', 'measure_time', 'pressure'])
df.set_index('measure_id', inplace=True)
print('df:\n', df)

我需要为每一行计算所有先前行的时间滚动总和,这就是区别:

measure_time of current row - measure_time of precedent row

低于某个值(例如 2 分钟),当前行包含在总和中。 这将在此处给出 rolling_sum 列:

data = {'measure_id': ['0', '1', '2', '3', '4'],
        'measure_time': ['2019-11-22 22:30:08.559000', '2019-11-22 22:36:09.149000', '2019-11-22 22:36:09.149000', '2019-11-22 22:40:09.261000', '2019-11-22 22:46:10.011000'],
        'pressure': [10, 9, 3, 11, 12],
        'rolling_sum':[10, 9, 12, 11, 12]}
df = pd.DataFrame(data, columns=['measure_id', 'measure_time', 'pressure', 'rolling_sum'])
df.set_index('measure_id', inplace=True)
print('df:\n', df)

现在看来 Pandas 可以处理带偏移量的滚动了 Pandas: rolling mean by time interval ,但我无法让这个解决方案在这里工作(可能是因为非时间索引)。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    首先您应该将measure_time 列转换为日期类型:

    df['measure_time'] = pd.to_datetime(df['measure_time'])
    

    那么你可以在这样的列上使用rolling方法,基于时差如下:

    result_df = df.rolling('2s', on='measure_time').sum()
    
    result_df
    
                       measure_time     pressure
    measure_id                                  
    0          2019-11-22 22:30:08.559      10.0
    1          2019-11-22 22:36:09.149       9.0
    2          2019-11-22 22:36:09.149      12.0
    3          2019-11-22 22:40:09.261      11.0
    4          2019-11-22 22:46:10.011      12.0
    
    
    

    2s 表示 2 秒窗口。

    【讨论】:

      猜你喜欢
      • 2015-03-13
      • 1970-01-01
      • 2021-04-24
      • 2013-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-09
      • 1970-01-01
      相关资源
      最近更新 更多