gpt4 book ai didi

python - 我可以按列分组并重新采样日期吗?

转载 作者:太空宇宙 更新时间:2023-11-04 02:52:34 25 4
gpt4 key购买 nike

我有一些消费者购买数据看起来像

CustomerID  InvoiceDate
13654.0 2011-07-17 13:29:00
14841.0 2010-12-16 10:28:00
19543.0 2011-10-18 16:58:00
12877.0 2011-06-15 13:34:00
15073.0 2011-06-06 12:33:00

我对客户的购买率很感兴趣。我想按每个客户分组,然后确定每个季度购买了多少商品(假设每个季度从 1 月开始每 3 个月一次)。

我可以只定义每个季度的开始和结束时间,然后制作另一列。我想知道我是否可以改用 groupby 来实现相同的目的。

目前,我是这样做的:

r = data.groupby('CustomerID')

frames = []
for name,frame in r:

f =frame.set_index('InvoiceDate').resample("QS").count()

f['CustomerID']= name

frames.append(f)


g = pd.concat(frames)

最佳答案

更新:

In [43]: df.groupby(['CustomerID', pd.Grouper(key='InvoiceDate', freq='QS')]) \
.size() \
.reset_index(name='Count')
Out[43]:
CustomerID InvoiceDate Count
0 12877.0 2011-04-01 1
1 13654.0 2011-07-01 1
2 14841.0 2010-10-01 1
3 15073.0 2011-04-01 1
4 19543.0 2011-10-01 1

这是你想要的吗?

In [39]: df.groupby(pd.Grouper(key='InvoiceDate', freq='QS')).count()
Out[39]:
CustomerID
InvoiceDate
2010-10-01 1
2011-01-01 0
2011-04-01 2
2011-07-01 1
2011-10-01 1

关于python - 我可以按列分组并重新采样日期吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43397619/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com