我想使用python 2.7将csv文件转换为json文件。下面是我试过的python代码,但它没有给我预期的结果。另外,我想知道是否有比我简化的版本。任何帮助表示赞赏。
import pandas as pd
from itertools import groupby
import json
df = pd.read_csv('SampleCsvFile.csv')
names = df.columns.values.tolist()
data = df.values
master_list2 = [ (d["zipcode"], d["state"], d) for d in [dict(zip(names, d)) for d in data] ]
intermediate2 = [(k, [x[2] for x in list(v)]) for k,v in groupby(master_list2, lambda t: (t[0],t[1]) )]
nested_json2 = [dict(zip(names,(k[0][0], k[0][1], k[1]))) for k in [(i[0], i[1]) for i in intermediate2]]
#print json.dumps(nested_json2, indent=4)
with open('ExpectedJsonFile.json', 'w') as outfile:
outfile.write(json.dumps(nested_json2, indent=4))
{{1}}
{{1}}
答案 0 :(得分:2)
由于你已经在使用pandas,我试图从数据帧方法中获得尽可能多的里程数。我也最终在你的实施中徘徊相当远的地方。不过,我认为这里的关键是不要试图让你的列表和/或词典理解变得过于聪明。您可以很容易地将自己和每个阅读代码的人混淆。
import pandas as pd
from itertools import groupby
from collections import OrderedDict
import json
df = pd.read_csv('SampleCsvFile.csv', dtype={
"zipcode" : str,
"date" : str,
"state" : str,
"val1" : str,
"val2" : str,
"val3" : str,
"val4" : str,
"val5" : str
})
results = []
for (zipcode, state), bag in df.groupby(["zipcode", "state"]):
contents_df = bag.drop(["zipcode", "state"], axis=1)
subset = [OrderedDict(row) for i,row in contents_df.iterrows()]
results.append(OrderedDict([("zipcode", zipcode),
("state", state),
("subset", subset)]))
print json.dumps(results[0], indent=4)
#with open('ExpectedJsonFile.json', 'w') as outfile:
# outfile.write(json.dumps(results[0], indent=4))
将所有json数据类型写为字符串并保留其原始格式的最简单方法是强制read_csv
将它们解析为字符串。但是,如果在写出json之前需要对值进行任何数值处理,则必须允许read_csv
以数字方式解析它们并在转换为json之前将它们强制转换为正确的字符串格式。