gpt4 book ai didi

python - 使用 Python 中的数组对象将 csv 转换为 JSON

转载 作者:行者123 更新时间:2023-12-04 07:29:06 24 4
gpt4 key购买 nike

使用子列表数组将 CSV 文件转换为 JSON 时遇到问题。
CSV输入:

Id,Name,Sub1,Sub2
1,A,Mathematics,English
2,B,Mathematics,Science
JSON 输出:
{
"sources": [
{
"Id": 1,
"Name": "A",
"subjects": [
{
"Sub1": "Mathematics",
"Sub2": "English"
}
]
},
{
"Id": 2,
"Name": "B",
"subjects": [
{
"Sub1": "Mathematics",
"Sub2": "Science"
}
]
}
]
}
尝试使用以下 pands 但需要改进它
import pandas as pd
csv_file = pd.DataFrame(pd.read_csv("/home/ubuntu/Proj/sample_2.csv", sep = ",", header = 0, index_col = False))

csv_file.to_json("/home/ubuntu/Proj/csvToJson_2.json", indent=4, orient = "records", date_format = "epoch", double_precision = 10, force_ascii = True, date_unit = "ms", default_handler = None)

最佳答案

您可以使用 DataFrame.apply() 使用 lambda 函数制作自定义格式,然后使用 json.dump写成json文件,如下:

csv_file = pd.read_csv("/home/ubuntu/Proj/sample_2.csv", sep = ",", header = 0, index_col = False)

json_out_list = csv_file.apply(lambda x: {"Id": x['Id'], "Name": x['Name'], "subjects": [{"Sub1": x['Sub1'], "Sub2": x['Sub2']}]}, axis=1).to_list()

json_result = {"sources": json_out_list}

import json
with open("/home/ubuntu/Proj/csvToJson_2.json", 'w') as f:
json.dump(json_result, f, indent=2)
结果:
{
"sources": [
{
"Id": 1,
"Name": "A",
"subjects": [
{
"Sub1": "Mathematics",
"Sub2": "English"
}
]
},
{
"Id": 2,
"Name": "B",
"subjects": [
{
"Sub1": "Mathematics",
"Sub2": "Science"
}
]
}
]
}

关于python - 使用 Python 中的数组对象将 csv 转换为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68048479/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com