要列出json文件的pandas列



从一个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'])

最新更新