首页 > 解决方案 > 尝试对数据框进行分组并计算类别的出现次数

问题描述

我想按客户分组并计算他们在每家商店购买了多少次。而且每家店都应该有自己的专栏

原始数据框:

  customer        store  transaction value
0     John          KFC                  5
1     John    McDonalds                  5
2     John          KFC                  6
3     Mary          KFC                  3
4     Mary    McDonalds                  5
5     Mary  Burger King                  1
6    Peter    McDonalds                  2
7    Peter    McDonalds                  5
8    Peter    McDonalds                  8
9    Peter          KFC                  1

我的预期输出是:

customer    KFC McDonalds   Burger King
John         2         1       0
Mary         1         1       1
Peter        1         3       0

老实说,我不能 100% 确定要为此使用哪个 pandas 函数。我想我已经尝试了所有这些,包括melt但没有一个有效:

d.groupby(['customer','store']).agg({'store': ['count']})

d.groupby('customer').agg('count')

d.pivot(index='customer', columns='store', values='Amount')

我想我需要使用枢轴,但我无法弄清楚。

我的df:

pd.DataFrame({'customer': pd.Series(['John', 'John', 'John', 'Mary', 'Mary', 'Mary', 'Peter', 'Peter', 'Peter', 'Peter'],dtype='object',index=pd.RangeIndex(start=0, stop=10, step=1)), 'store': pd.Series(['KFC', 'McDonalds', 'KFC', 'KFC', 'McDonalds', 'Burger King', 'McDonalds', 'McDonalds', 'McDonalds', 'KFC'],dtype='object',index=pd.RangeIndex(start=0, stop=10, step=1)), 'transaction value': pd.Series([5, 5, 6, 3, 5, 1, 2, 5, 8, 1],dtype='int64',index=pd.RangeIndex(start=0, stop=10, step=1))}, index=pd.RangeIndex(start=0, stop=10, step=1))

标签: pythonpandas

解决方案


推荐阅读