python – pandas计算每个日期的最后7天的值

有两个Dataframe.首先是这样的:

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

我正在尝试从每个df1 [‘month’]的第一天起最后7天获得名为’last_week_buys’的新df2列,其中包含聚合购买.换句话说,我想得到这个:

        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值.

点赞