我有一个看起来像这样的数据框
customerId Date Amount_Spent
123 01/01/2018 500
456 01/01/2018 250
123 02/01/2018 300
456 02/01/2018 100
我想统计连续两天消费超过 200 的客户(不同/非不同)。
所以我希望得到
customerId Date1 Date2 Total_Amount_Spent
123 01/01/2018 02/01/2018 800
有人可以帮我解决这个问题吗?
最佳答案
有两种检查,一种检查天数差异,另一种是使用 all
检查金额始终超过 100,然后这两种情况都满足我们选择 ID。
s=df.groupby('customerId').agg({'Date':lambda x : (x.iloc[0]-x.iloc[-1]).days==-1,'Amount_Spent':lambda x : (x>100).all()}).all(1)
newdf=df.loc[df.customerId.isin(s.index),]
newdf
Out[1242]:
customerId Date Amount_Spent
0 123 2018-01-01 500
2 123 2018-01-02 300
<小时/>
再次使用groupby
+ agg
来获取您需要的格式
newdf.groupby('customerId').agg({'Date':['first','last'],'Amount_Spent':'sum'})
Out[1244]:
Date Amount_Spent
first last sum
customerId
123 2018-01-01 2018-01-02 800
关于Python Pandas 使用滚动时间窗口进行计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53707956/