本文介绍了Python3 - 使用pandas将csv转换为json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
soive有一个 .csv
文件有5列,但我只需要 json
文件包含3这些我将如何做呢?
so ive got a .csv
files with 5 columns but i only need the json
file to contain 3 of these how would i go about doing it?
csv文件:
Ncode Ocode name a b c
1 1.1 1x 1a 1b 1c
2 2.2 2x 2a 2b 2c
3 3.3 3x 3a 3b 3c
Json输出:
{1.1:[{a: {a:2a},{b:2b},b:a},{b:1b},{c:1c {c:2c}]}
推荐答案
txt = """Ncode Ocode name a b c
1 1.1 1x 1a 1b 1c
2 2.2 2x 2a 2b 2c
3 3.3 3x 3a 3b 3c
"""
df = pd.read_csv(StringIO(txt), delim_whitespace=True)
json.dumps(
{'{:0.2f}'.format(r.Ocode): [{'a': r.a}, {'b': r.b}, {'c': r.c}]
for r in df.itertuples()}
)
'{"2.20": [{"a": "2a"}, {"b": "2b"}, {"c": "2c"}], "3.30": [{"a": "3a"}, {"b": "3b"}, {"c": "3c"}], "1.10": [{"a": "1a"}, {"b": "1b"}, {"c": "1c"}]}'
这篇关于Python3 - 使用pandas将csv转换为json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!