python - pandas 计算每个日期最近 7 天的值

标签 python pandas python-datetime

有两个数据框。首先是这样的:

print df1

        id        date    month  is_buy
     0  17  2015-01-16  2015-01       1
     1  17  2015-01-26  2015-01       1
     2  17  2015-01-27  2015-01       1
     3  17  2015-02-11  2015-02       1
     4  17  2015-03-14  2015-03       1
     5  18  2015-01-28  2015-01       1
     6  18  2015-02-12  2015-02       1
     7  18  2015-02-25  2015-02       1
     8  18  2015-03-04  2015-03       1

在第二个数据框中,有一些从第一个数据框中按月汇总的数据:

df2 = df1[df1['is_buy'] == 1].groupby(['id', 'month']).agg({'is_buy': np.sum})

print df2

        id    month       buys
     0  17  2015-01          3
     1  17  2015-02          1
     2  17  2015-03          1
     3  18  2015-01          1
     4  18  2015-02          2
     5  18  2015-03          1

我正在尝试获取名为“last_week_buys”的新 df2 列,其中包含从每个 df1['month'] 的第一天算起的过去 7 天的总购买量。换句话说,我想得到这个:

        id    month       buys    last_week_buys
     0  17  2015-01          3               NaN
     1  17  2015-02          1                 2
     2  17  2015-03          1                 0
     3  18  2015-01          1               NaN
     4  18  2015-02          2                 1
     5  18  2015-03          1                 1

有什么想法可以得到这个专栏吗?

最佳答案

这可以通过一些日期操作魔法和分组来完成:

# datetimeindex makes convenient manipulations
date = pd.DatetimeIndex(df1['date'])

# compute df2: totals by month
df1['month'] = date.to_period('M')
df2 = df1[df1['is_buy'] == 1].groupby(['id', 'month']).sum()

# compute df3: totals by last seven days
from datetime import timedelta
is_last_seven = date.to_period('M') != (date + timedelta(days=7)).to_period('M')
df3 = df1[(df1['is_buy'] == 1) & is_last_seven].groupby(['id', df1.month + 1]).sum()

# join the results
result = df2.join(df3, rsuffix='_last_seven')

结果如下:

>>> print(result)

            is_buy  is_buy_last_seven
id month                             
17 2015-01       3                NaN
   2015-02       1                  2
   2015-03       1                NaN
18 2015-01       1                NaN
   2015-02       2                  1
   2015-03       1                  1

然后您可以根据需要填充 NaN 值。

关于python - pandas 计算每个日期最近 7 天的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33914458/

相关文章:

python - 获取两个单独查询之间的增量

python - 在 pandas 中查找具有不同列名的值

python - Pandas :如何在保持列成对的同时按列组取消堆叠

python - 如何在 dask 数据框中添加反射(reflect)日期值(来自列)是否是假期成员的列

Python 日期时间与顺序问题

python - 实体引用和 lxml

python - 如何在 Django ORM 中加入子查询

python - 我可以在 C 中使用 Python/Ruby ORM 吗?

python - 根据组绘制条形图

python - 时区问题 - 所有时区都是本地时区?