python - 按每个唯一 ID 分组,然后查找每个品牌的购买次数
问题描述
我有过去 3 年的客户购买数据。下面的示例:
customer_id|date |sales_amount|product_type
479485 |20190120 | 500 | bags
479485 |20180320 | 200 | clothes
479485 |20180321 | 200 | clothes
472848 |20191020 | 100 | clothes
我想为每个唯一的客户 ID 查找他们在三年内针对不同产品类型进行的交易次数。理想情况下,每个唯一客户 ID 的产品类型的价值计数。所以对于customer_id
= 479485 的输出:
customer_id
479485 |bags | 1
|clothes | 2
我试过做一个数据透视表,但它没有给我理想的结果:
pd.pivot_table(clusters, index=['customer_id', 'product_type'], aggfunc='sum')
奖金:如果我想做同样的事情,但看它但按年份分开,这可能吗?
解决方案
假设输入数据是这样的:
df=pd.DataFrame({'cust_id':[479485,479485,479485,472848],
'date':['20190120','20180320','20180321','20191020'],
'sales_amount':[500,200,200,100],
'product_type':['bags','clothes','clothes','clothes']})
我会做这样的事情:
df.groupby(['cust_id','product_type'])['sales_amount'].count()
按年份分组当然是可能的。有几个选项,但您必须查看日期时间库以将日期列转换为日期时间对象,然后进行处理。
推荐阅读
- java - 为什么我的数据库没有正确更新我的值?
- php - 不显示我的参考链接
- python - 仅对时间序列中的某些数据点应用校正,这些数据点通过值快速下降来识别
- python - ValueError:输入数组应具有与目标数组相同数量的样本。找到 1600 个输入样本和 1800 个目标样本
- xml - ant 编译没有显示类
- c# - Unity:如何将 AssetBundle 构建到每个 AssetBundle 的单独目录中
- javascript - Discord.js 和 discord.js-commando 防止命令在特定通道中运行
- c# - 将 aspnet 核心作为服务运行 - nssm 与 RunAsService
- merge - SAS:合并具有不同名称的相同变量的两个数据集
- python - 操纵原始数据包以具有 NAT 功能