首页 > 解决方案 > 将具有 NaN 的 pandas 数据帧转换为深度 >=2 的嵌套 json

问题描述

我的数据框如下,带有 NaN 值。

Category,Type,Capacity,Efficiency  
Chiller,ChillerA,1000,6.0  
Chiller,ChillerB,2000,5.5  
Cooling Tower,Cooling TowerA,1000,NaN  
Cooling Tower,Cooling TowerB,2000,NaN  

我想将此熊猫数据框转换为以下 json 格式。
谁能告诉我如何实现这个?

{
    "Chiller":{
        "ChillerA":{
            "Capacity":1000,
            "Efficiency":6.0
        },
        "ChillerB":{
            "Capacity":2000,
            "Efficiency":5.5
        },
    },
    "Cooling Tower":{
        "Cooling TowerA":{
            "Capacity":1000 <=Will not include efficiency because efficiency was NaN for this.

        },
        "Cooling TowerB":{
            "Capacity":2000
        },
    },
}

标签: pythonjsonpandas

解决方案


这是一个非常强大的解决方案,可以使用嵌套的 dict 理解获得所需的输出:

df = df.set_index(['Category', 'Type'])
{level: {chiller: {name: value for name, value in values.items() if not np.isnan(value)} for chiller, values in df.xs(level).to_dict('index').items()} for level in df.index.levels[0]}
#{'Cooling Tower':
#    {'Cooling TowerA':
#       {'Capacity': 1000.0},
#    'Cooling TowerB':
#        {'Capacity': 2000.0}},
# 'Chiller':
#    {'ChillerA': {'Efficiency': 6.0, 'Capacity': 1000.0},
#     'ChillerB': {'Efficiency': 5.5, 'Capacity': 2000.0}}}

推荐阅读