python - 将具有 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
},
},
}
解决方案
这是一个非常强大的解决方案,可以使用嵌套的 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}}}
推荐阅读
- c - 如何阻止 GCC 将此逐字节复制优化为 memcpy 调用?
- java - 通过 ojdbc 连接到 oracle 数据库 12c 时出现用户名和密码问题
- python - 私有 S3 存储桶的预签名 URL 显示 AWS 访问密钥 ID 和存储桶名称。这是一个安全问题吗?
- wordpress - 使 Wordpress 后编辑左侧列以小分辨率位于右侧列的顶部
- python - 如何使用 Python 以编程方式在 Mac 上聚焦窗口?
- python - 调整窗口大小时如何使布局均匀扩展?
- javascript - 页面刷新时随机图像显示顺序
- keras - 如何使用使用特征层的训练模型进行预测?
- ios - Ionic 4 网络接口为 IP 地址返回 0.0.0.0。如何返回实际IP地址?
- python - 如何使用正则表达式提取人名?