Python3 - 使用熊猫将 csv 转换为 json
Posted
技术标签:
【中文标题】Python3 - 使用熊猫将 csv 转换为 json【英文标题】:Python3 - convert csv to json using pandas 【发布时间】:2017-06-04 06:27:30 【问题描述】:我有一个包含 5 列的 .csv
文件,但我只需要 json
文件来包含其中的 3 个,我该怎么做?
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":"1a","b":"1b","c":"1c"],"2.2":["a":"2a","b":"2b","c":"2c"]
【问题讨论】:
"1.1":"a":"1a","b":"1b","c":"1c","2.2":"a":"2a","b":"2b","c":"2c"
想要这个吗?
@MYGz,是的,但是需要有一个 [ ] 包围 Ocode 的条目......所以你的建议是这样的; "1.1":"a":"1a","b":"1b","c":"1c","2.2":"a":"2a","b":"2b","c":"2c"
,我需要的是"1.1":["a":"1a","b":"1b","c":"1c"],"2.2":["a":"2a","b":"2b","c":"2c"]
谢谢
【参考方案1】:
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 - 使用熊猫将 csv 转换为 json的主要内容,如果未能解决你的问题,请参考以下文章