[英]pandas column to list for a json file
from a Dataframe, I want to have a JSON output file with one key having a list:从 Dataframe 中,我想要一个 JSON output 文件,其中一个键具有一个列表:
Expected output:预期 output:
[
{
"model": "xx",
"id": 1,
"name": "xyz",
"categories": [1,2],
},
{
...
},
]
What I have:我有的:
[
{
"model": "xx",
"id": 1,
"name": "xyz",
"categories": "1,2",
},
{
...
},
]
The actual code is:实际代码是:
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)
How can I achive this easily?我怎样才能轻松做到这一点?
You can use:您可以使用:
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(',')])
df.to_json('output.json', orient='records', indent=4)
Content of output.json
output.json
的内容
[
{
"model":"xx",
"id":1,
"name":"xyz",
"categories":[
1,
2
]
}
]
Note you can also use:请注意,您还可以使用:
df['categories'] = pd.eval(df['categories'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.