python - 按组划分的 Pandas 时间累计和

标签 python pandas group-by time-series

我有一个数据框,其中为每个 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/

相关文章:

python - 如何并行运行函数?

r - 根据 R 中函数给定的组的因子获取多列的百分比值

SQL SELECT with GROUP BY,返回到组

python - 3d 内核和 3d 图像(例如 RGB)的矩阵乘法到底是如何产生 2d 输出的?

python - 有没有办法验证从源代码构建的 Python 解释器是否正确?

python - Flask SQLAlchemy - 2013 失去连接

python - pandas.shift 到底如何工作?

python - 为什么这个 CountVectorizer 输出与我的字数统计不同?

python - 使用另一个时间戳数据帧来过滤 pandas 上的时间戳数据帧

计数不同时的 MySQL 案例