[英]How to convert this CSV into Json?
如何將此CSV轉換為自定義JSON格式,(我已經在下面附加了我的代碼研究,無法獲得所需的輸出結構)我在pandas數據框架中有csv
將此csv轉換為json
期待從csv到json
[
{
"name": "your_name",
"email": "your_email"
},
[
[
{
"col1": "Phoebe",
"col2": "Oh my God, he\u0092s lost it. He\u0092s totally lost it.",
"col3": "PREDICTED_EMOTION"
},
{
"col1": "Monica",
"col2": "What?",
"col3": "PREDICTED_EMOTION"
},
.....
鑒於:
$ cat x.csv
col1 col2 col3
0.123 this is a text txt
0.987 whatever this is spam
0.429 yummy, frites fries
對於列為json鍵:
>>> import pandas as pd
>>> df = pd.read_csv('x.csv', sep='\t')
>>> df
col1 col2 col3
0 0.123 this is a text txt
1 0.987 whatever this is spam
2 0.429 yummy, frites fries
>>> df.to_json()
'{"col1":{"0":0.123,"1":0.987,"2":0.429},"col2":{"0":"this is a text","1":"whatever this is","2":"yummy, frites"},"col3":{"0":"txt","1":"spam","2":"fries"}}'
對於行作為json鍵:
>>> df.T
0 1 2
col1 0.123 0.987 0.429
col2 this is a text whatever this is yummy, frites
col3 txt spam fries
>>> df.T.to_json()
'{"0":{"col1":0.123,"col2":"this is a text","col3":"txt"},"1":{"col1":0.987,"col2":"whatever this is","col3":"spam"},"2":{"col1":0.429,"col2":"yummy, frites","col3":"fries"}}'
期望的json是結構不良的json。 大熊貓給出的默認值更合理。
如果你真的想要輸出OP,那么:
>>> from pprint import pprint
>>> import json
>>> import pandas as pd
>>> df = pd.read_csv('x.csv', sep='\t')
>>> tmp_json = df.T.to_json()
>>> tmp_json
'{"0":{"col1":0.123,"col2":"this is a text","col3":"txt"},"1":{"col1":0.987,"col2":"whatever this is","col3":"spam"},"2":{"col1":0.429,"col2":"yummy, frites","col3":"fries"}}'
>>> [v for k,v in eval(tmp_json).items()]
[{'col1': 0.123, 'col2': 'this is a text', 'col3': 'txt'}, {'col1': 0.987, 'col2': 'whatever this is', 'col3': 'spam'}, {'col1': 0.429, 'col2': 'yummy, frites', 'col3': 'fries'}]
>>> json.dumps([{"name": "your_name", "email": "your_email"}, tmp_json_dict])
'[{"name": "your_name", "email": "your_email"}, [{"col1": 0.123, "col2": "this is a text", "col3": "txt"}, {"col1": 0.987, "col2": "whatever this is", "col3": "spam"}, {"col1": 0.429, "col2": "yummy, frites", "col3": "fries"}]]'
>>> op_desired_json = json.dumps([{"name": "your_name", "email": "your_email"}, tmp_json_dict])
>>> pprint(eval(op_desired_json))
[{'email': 'your_email', 'name': 'your_name'},
[{'col1': 0.123, 'col2': 'this is a text', 'col3': 'txt'},
{'col1': 0.987, 'col2': 'whatever this is', 'col3': 'spam'},
{'col1': 0.429, 'col2': 'yummy, frites', 'col3': 'fries'}]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.