使用NaN将pandas数据框转换为深度> = 2的嵌套json

时间:2018-09-04 13:51:49

标签: python json pandas

我的数据框如下,具有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
        },
    },
}

1 个答案:

答案 0 :(得分:2)

这是一个非常强大的解决方案,可以使用嵌套的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}}}