如何使用Pandas将CSV转换为含重复嵌套键名的JSON文件
Pandas CSV转JSON嵌套对象重命名键解决方案
运行环境:Python 3.9.5 / Pandas 1.1.3
你只需要在生成org_2嵌套对象时,先把选中的列重命名再转字典即可,无需修改原始CSV表头。同时注意原有代码导出JSON时没有包含location字段,需要补充到导出列列表中,才能匹配你给出的预期输出。
修改后的完整代码如下:
import pandas as pd import json import os csv = "/Users/me/file.csv" csv_file = pd.read_csv(csv, sep=",", header=0, index_col=False) # 生成org嵌套对象,逻辑不变 csv_file['org'] = csv_file[['data', 'type']].apply(lambda s: s.to_dict(), axis=1) # 生成org_2嵌套对象时,先重命名索引再转字典,替换原有键名 csv_file['org_2'] = csv_file[['data1', 'type1']].apply(lambda s: s.rename({'data1':'data', 'type1':'type'}).to_dict(), axis=1) # 导出时补充location列,匹配预期输出 csv_file[['id', 'location', 'org', 'org_2']].to_json( "file.json", orient="records", lines=True, date_format="iso", double_precision=10, force_ascii=True, date_unit="ms", default_handler=None )
如果你的数据量较大,不想用apply逐行处理提升效率,也可以用更直接的字典构造方式替换逻辑:
# 替换原来的两行apply逻辑,性能更优 csv_file['org'] = csv_file.apply(lambda x: {'data': x['data'], 'type': x['type']}, axis=1) csv_file['org_2'] = csv_file.apply(lambda x: {'data': x['data1'], 'type': x['type1']}, axis=1)
内容的提问来源于stack exchange,提问作者Stpete111
相关产品推荐
相关产品推荐

