[英]Convert pandas dataframe with NaN to nested json with depth >=2
I have dataframe as below with NaN value. 我有下面的数据框与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
I want to convert this pandas dataframe to below json format. 我想将此熊猫数据帧转换为以下json格式。
Can anyone tell me how to implement this? 谁能告诉我如何执行此操作?
{
"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
},
},
}
This is a very robust solution that will get you to desired output using nested dict comprehension: 这是一个非常强大的解决方案,可以使用嵌套的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}}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.