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

2024-10-01 09:33:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些消费者购买数据

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)

Tags: 数据nameframes客户定义时间消费者frame
2条回答

我想这是我能做的最好的:

data.groupby('CustomerID').apply(lambda x: x.set_index('InvoiceDate').resample('QS').count())

更新:

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

相关问题 更多 >