首页 > 解决方案 > 如何遍历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
          

标签: jsonpandas

解决方案


您可以读取您的 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']]

推荐阅读