Python Pandas 使用滚动时间窗口进行计数

标签 python pandas dataframe

我有一个看起来像这样的数据框

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/

相关文章:

python - 在数据框中搜索子字符串并替换它

python - Twisted:WAITING延迟到 'finish'

python - 如何从 C 扩展模块中的 __future__ 导入

python - 按 pandas 数据框中的字段分组

python - 将旋转矩阵应用于 xy 坐标

python - 如何检查 n 列表并将其转换为 Python 中的 pandas 数据框?

python-3.x - 如何使用 python 对数据帧之间的降序进行排序

r - 数据框列的平均值

python - 如何从 Google Chrome Selenium Webdriver 客户端获取 JSON 响应?

python - 在python中将包装为字符串的元组转换为元组的简单方法