【问题标题】:Nested dictionary from 3 columns, one of which with repeating categories by top-level dictionary key3列的嵌套字典,其中一列通过顶级字典键重复类别
【发布时间】: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


    【解决方案1】:

    使用pivot 转换为dict:

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

    【讨论】:

      猜你喜欢
      • 2022-10-16
      • 1970-01-01
      • 2020-12-15
      • 2021-05-10
      • 2013-01-19
      • 2016-01-07
      • 2019-06-04
      相关资源
      最近更新 更多