要为 json 文件列出的 pandas 列

pandas column to list for a json file

从 Dataframe 中,我想要一个 JSON 输出文件,其中一个键有一个列表:

预期输出:

[
  {
    "model": "xx",
    "id": 1,
    "name": "xyz",
    "categories": [1,2],
  },
  {
    ...
  },
]

我有:

[
  {
    "model": "xx",
    "id": 1,
    "name": "xyz",
    "categories": "1,2",
  },
  {
    ...
  },
]

实际代码是:

df = pd.read_excel('data_threated.xlsx')
result = df.reset_index(drop=True).to_json("output_json.json", orient='records')
parsed = json.dumps(result)

jsonfile = open("output_json.json", 'r')
data = json.load(jsonfile)

我怎样才能轻松做到这一点?

编辑:

print(df['categories'].unique().tolist())

['1,2,3', 1, nan, '1,2,3,6', 9, 8, 11, 4, 5, 2, '1,2,3,4,5,6,7,8,9']

您可以使用:

df = pd.read_excel('data_threated.xlsx').reset_index(drop=True)
df['categories'] = df['categories'].apply(lambda x: [int(i) for i in x.split(',')] if isinstance(x, str) else '')
df.to_json('output.json', orient='records', indent=4)

output.json

的内容
[
    {
        "model":"xx",
        "id":1,
        "name":"xyz",
        "categories":[
            1,
            2
        ]
    }
]

注意你也可以使用:

df['categories'] = pd.eval(df['categories'])