json - 如何遍历json并创建数据框
问题描述
我有一个像下面这样的 JSON 文件,我怎样才能从中制作一个数据框。我想将主键设为索引,将子键设为列。
{
"PACK": {
"labor": "Recycle",
"actual": 0,
"Planned": 2,
"max": 6
},
"SORT": {
"labor": "Mix",
"actual": 10,
"Planned": 4,
"max": 3
}
}
预期的输出类似于,我尝试使用df.T
但不起作用。对此的任何帮助表示赞赏。
actual planned
PACK 0 2
SORT 10 4
解决方案
您可以读取您的 json 文件以进行 dict。然后创建数据框,其中 dict 值作为数据,dict 键作为索引。
import json
import pandas as pd
with open('test.json') as f:
data = json.load(f)
df = pd.DataFrame(data.values(), index=data.keys())
print(df)
labor actual Planned max
PACK Recycle 0 2 6
SORT Mix 10 4 3
选择列
df = df[['actual', 'planned']]
推荐阅读
- javascript - 在已运行的 lightGallery 实例中添加/编辑选项
- sml - 是什么导致我的 SML 变量未绑定?
- python - 如何防止第二个for循环减慢服务返回的数据
- gstreamer - 使用 udp 启动 rtp
- windows - 如何处理勺子错误:Redis 中的权限被拒绝
- jquery - jQuery:如何打开一个新的模态对话框或弹出窗口
- mongodb - 将 MongoDB 从 root 更改为 Sudo 用户
- testing - 带有 Electron 的 TestCafe:无法加载主页(主页可能返回“304”http 代码)
- php - SQL 选择 - 多个孩子
- angular - Bootstrap Angular Stepper 的材料设计不起作用