我有如下带有 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
},
},
}
这是一个非常强大的解决方案,可以使用嵌套的 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}}}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句