python - 3列的嵌套字典,其中一列通过顶级字典键重复类别
问题描述
我的数据框:
| Name | Greenhouse Gas | Quantity |
|:------|:--------------:|---------:|
| Chair | Methane | 0.5 |
| Chair | CO2 | 0.4 |
| Chair | Other | 0.6 |
| House | Methane | 0.2 |
| House | CO2 | 0.4 |
| House | Other | 0.3 |
试图获得输出:
{Name:{Methane:#, CO2:#, Other:#},Name:{Methane:#, CO2:#, Other:#}}
例如
{Chair:{Methane: 0.5, CO2: 0.4, Other:0.6},House:{Methane:0.2, CO2:0.4, Other: 0.3}}
试过:
df.groupby('Name')[['Greenhouse Gas','Quantity']].apply(lambda x: x.set_index('Greenhouse Gas').to_dict(orient='index')).to_dict()
但是,我不断得到一个结构如下的字典:
{Name: {Methane:{"Quantity":#}, CO2:{"Quantity":#}, Other:{"Quantity":#}}
任何有关如何调整我的方法的指导将不胜感激!干杯!
解决方案
使用pivot
转换为字典:
>>> df.pivot(index='GreenhouseGas', columns='Name', values='Quantity').to_dict()
{'Chair': {'CO2': 0.4, 'Methane': 0.5, 'Other': 0.6},
'House': {'CO2': 0.4, 'Methane': 0.2, 'Other': 0.3}}
推荐阅读
- python - 根据条件将 df 中的列除以另一个 df 值
- python - 在python中解析html的问题
- iframe - 即使父 url 是用 https 加载的,iframe 也会将相对 url 加载为 http
- node.js - 如何实现射击和碰撞
- amazon-s3 - 尝试使用以下配置创建 S3 存储桶时,继续遇到此错误:模板验证错误
- mysql - MariaDb 复制(具有私有 ip 的主控)
- python - 带有多个分隔符的 Pandas to_csv
- linux - 无法解决 TypeError:“NoneType”和“int”实例之间不支持“>”
- vb.net - 右侧有图片的标签控件不可见
- vim - 是否可以在vim中突出显示视口的中心线