【发布时间】:2018-02-21 13:57:23
【问题描述】:
我正在构建一个“外部连接”两个 csv 文件并将结果导出为 json 对象的过程。
# read the source csv files
firstcsv = pandas.read_csv('file1.csv', names = ['main_index','attr_one','attr_two'])
secondcsv = pandas.read_csv('file2.csv', names = ['main_index','attr_three','attr_four'])
# merge them
output = firstcsv.merge(secondcsv, on='main_index', how='outer')
jsonresult = output.to_json(orient='records')
print(jsonresult)
现在,两个csv文件是这样的:
file1.csv:
1, aurelion, sol
2, lee, sin
3, cute, teemo
file2.csv:
1, midlane, mage
2, jungler, melee
我希望生成的 json 输出如下:
[{"main_index":1,"attr_one":"aurelion","attr_two":"sol","attr_three":"midlane","attr_four":"mage"},
{"main_index":2,"attr_one":"lee","attr_two":"sin","attr_three":"jungler","attr_four":"melee"},
{"main_index":3,"attr_one":"cute","attr_two":"teemo"}]
相反,我使用 main_index = 3 上线
{"main_index":3,"attr_one":"cute","attr_two":"teemo","attr_three":null,"attr_four":null}]
所以空值会自动添加到输出中。 我想删除它们 - 我环顾四周,但找不到合适的方法。
希望有人可以帮助我!
【问题讨论】:
标签: python json csv null output