首页 > 解决方案 > 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":#}}

任何有关如何调整我的方法的指导将不胜感激!干杯!

标签: pythonpython-3.xpandasdataframedictionary

解决方案


使用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}}

推荐阅读