我有一个数据框,其中为每个 ID 记录了 1 个或多个事件。对于每个事件,记录 id、度量 x 和日期。像这样:
import pandas as pd
import datetime as dt
import numpy as np
x = range(0, 6)
id = ['a', 'a', 'b', 'a', 'b', 'b']
dates = [dt.datetime(2012, 5, 2),dt.datetime(2012, 4, 2),dt.datetime(2012, 6, 2),
dt.datetime(2012, 7, 30),dt.datetime(2012, 4, 1),dt.datetime(2012, 5, 9)]
df =pd.DataFrame(np.column_stack((id,x,dates)), columns = ['id', 'x', 'dates'])
我希望能够设置一个回溯期(即 70 天),并为数据集中的每一行计算该 ID 的任何先前事件的 x 的累积总和,并且在所需的回溯范围内(不包括 x对于正在执行计算的行)。 应该最终看起来像:
id x dates want
0 a 0 2012-05-02 00:00:00 1
1 a 1 2012-04-02 00:00:00 0
2 b 2 2012-06-02 00:00:00 9
3 a 3 2012-07-30 00:00:00 0
4 b 4 2012-04-01 00:00:00 0
5 b 5 2012-05-09 00:00:00 4
最佳答案
我需要执行类似的操作,所以我稍微看了看并在 pandas 的食谱(我热烈推荐给任何愿意了解这个包的所有伟大可能性的人)中找到了这个页面:Pandas: rolling mean by time interval .使用最新版本的 pandas,您可以将一个额外的参数传递给 rolling() 函数,该参数将用于计算基于类似 date_time 的列的 rolling() 函数。所以这个例子变得更直接了:
# First, convert the dates to date time to make sure it's compatible
df['dates'] = pd.to_datetime(df['dates'])
# Then, sort the time series so that it is monotonic
df.sort_values(['id', 'dates'], inplace=True)
# '70d' corresponds to the the time window we are considering
# The 'closed' parameter indicates whether to include the interval bounds
# 'yearfirst' indicates to pandas the format of your time series
df['want'] = df.groupby('id').rolling('70d', on='dates', closed='neither'
)['x'].sum().to_numpy()
df['want'] = np.where(df['want'].isnull(), 0, df['want']).astype(int)
df.sort_index() # to dispay it in the same order as the example provided
id x dates want
0 a 0 2012-05-02 1
1 a 1 2012-04-02 0
2 b 2 2012-06-02 9
3 a 3 2012-07-30 0
4 b 4 2012-04-01 0
5 b 5 2012-05-09 4
关于python - 按组划分的 Pandas 时间累计和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23836114/