【发布时间】:2021-07-22 20:09:38
【问题描述】:
我的数据框:
| 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":#}}
任何关于如何调整我的方法的指导将不胜感激!干杯!
【问题讨论】:
标签: python python-3.x pandas dataframe dictionary