【发布时间】:2021-03-27 00:21:45
【问题描述】:
我要计算:
- 每位客户在订阅前交易的非空月数(频率)
- 某一日期前的总交易金额栏(货币)
初始数据帧
ad = {'customer':['Clark','Stones','Fay','Stones','Clark','Clark','Clark','Fay','Stones'],
'subscribe_date':['2020-11-30','2020-07-01','2020-01-02','2020-07-01','2020-11-30','2020-11-30','2020-11-30',
'2020-01-02','2020-07-01'],
'trx_month':['2020-12-01','2020-07-01','2020-07-01','2021-03-01','2021-02-01','2020-09-01','2020-11-01',
'2020-08-01','2018-02-01'],
'trx_amount':[100,90,50,45,20,30,50,80,200],
}
ad = pd.DataFrame(ad)
ad = ad.sort_values(by=['customer','trx_month'])
预期的数据帧(之前)
ad2 = {'customer':['Clark','Stones','Fay'],
'subscribe_date':['2020-11-30','2020-07-01','2021-01-02'],
'frequency':[2,1,np.NaN], # number of months the customers transacted before the subscribe_date
'monetary':[80,200,np.NaN]} #sum of trx_amount before the subscribe_date
ad2 = pd.DataFrame(ad2)
ad2
ad3 = {'customer':['Clark','Stones','Fay'],
'subscribe_date':['2020-11-30','2020-07-01','2021-01-02'],
'frequency':[2,1,2], # number of months the customers transacted before the subscribe_date
'monetary':[120,45,130]} #sum of trx_amount before the subscribe_date
ad3 = pd.DataFrame(ad3)
ad3
说明: Clark 于 2020 年 11 月 30 日订阅。在订阅之前,他已在 2020 年 9 月和 11 月(频率 = 2)进行了交易,这些交易的总和为 80。 订阅后,他在2020年12月和2021年2月再次交易(频率=2,货币=120)
在不考虑订阅日期的情况下,使用pandas groupby可以计算频率和货币,但是有了新的限制,我很困惑。
如果代码可以灵活地调整到订阅后(比较前后效果),那就太好了。
【问题讨论】:
标签: python python-3.x pandas