python - Pandas groupby 通过另一列中的每个逗号分隔值来获取一列的总数
问题描述
从下面给定的示例数据集中,我想绘制一个聚集条形图,显示每个功能每年的总收入
-------------------------------
Year Product Feature Revenue
-------------------------------
2012 P1 a,d,e 98
2016 P2 a,b,c 167
2014 P3 d,e 120
2014 P4 a,c 144
2016 P5 b,c,d 156
2016 P6 e,a 107
绘制图表的数据可能是:
---------------------------------
Year | Feature_wise_total_revenue
---------------------------------
a b c d e
2012 98 0 0 98 98
2014 144 0 140 120 120
2016 274 323 323 156 107
请帮助从示例数据集中获取每个功能每年的总收入代码。
解决方案
尝试使用字符串访问器.str
, 和split
with explode
。groupby
和sum
与unstack
:_
df.assign(Feature=df['Feature'].str.split(',')).explode('Feature')\
.groupby(['Year','Feature'])['Revenue'].sum().unstack(1).fillna(0)
输出:
Feature a b c d e
Year
2012 98.0 0.0 0.0 98.0 98.0
2014 144.0 0.0 144.0 120.0 120.0
2016 274.0 323.0 323.0 156.0 107.0
绘图:
df_out.plot.bar()
推荐阅读
- python - Discord.py slot 命令添加表情符号的移动动画
- python - Float 16 量化 Tflite 模型不适用于自定义模型?
- arrays - 有没有办法改进这个pygame滤色器算法
- aspnetboilerplate - 缺少类型映射配置或不支持的映射。我的 aspnet 样板项目中的错误
- python - Python tkinter 保存到 txt 会创建不寻常的空行
- javascript - 在 Eclipse IDE 中找不到 javascript 项目
- python - 发生异常:AttributeError 'WebDriver' 对象没有属性 'link'
- linux - 如何知道一个进程在其所有执行时间内使用了多少资源?linux
- c# - 将力添加到刚体时,角色的行为很奇怪
- php - 请求中的 PHP SOAP EROOR