pandas 每个日期最近 7 天的计数值
pandas count values for last 7 days from each date
有两个数据框。首先是这样的:
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
值。
有两个数据框。首先是这样的:
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
值。