python - 尝试对数据框进行分组并计算类别的出现次数
问题描述
我想按客户分组并计算他们在每家商店购买了多少次。而且每家店都应该有自己的专栏
原始数据框:
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))
解决方案
推荐阅读
- kotlin - 如何根据动态创建的谓词集合过滤对象列表
- python - How to fill a circle with a gradient?
- ruby-on-rails - 我正在编写 Micheal Hartls Rail Tutorial 这本书我使用了相同的代码但得到了不同的结果
- ruby-on-rails - 如何在日志记录中过滤部分路径(不是参数)?
- flutter - 如何在 Flutter Web 中的 Row 中调整 IconButton 的大小?图标大小呈现在行视图之外
- laravel - 未找到 Laravel 5.8 类“Doctrine\DBAL\Driver\PDOMySql\Driver”
- python - 我需要我的代码只接受浮点值
- mysql - 连接到同一 DBMS 上的“外部”数据库
- java - 使用 Spring Boot 解析未转义的 Json
- javascript - 使用基本身份验证获取对 localhost 的请求