我有一个像下面这样的 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
答案 0 :(得分:3)
您可以将 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']]
答案 1 :(得分:2)
Pandas 可以读取多种格式的 JSON 文件。对于您的用例,以下选项应该以您想要的方式读取您的数据:
pd.read_json(json_file, orient="index")
有关 orient 选项的更多信息可以在 official documentation 中找到。