[英]How to convert this Json into CSV using python pandas?
試圖將這個大型json轉換為csv.Here是示例JSON
[
[{
"User": "Phoebe",
"text": "Oh my God, hes lost it. Hes totally lost it.",
"sent": "non-neutral"
},
{
"user": "Monica",
"text": "What?",
"sent": "surprise"
}
],
[{
"user": "Joey",
"text": "Hey Estelle, listen",
"sent": "neutral"
},
{
"user": "Estelle",
"text": "Well! Well! Well! Joey Tribbiani! So you came back huh? They",
"sent": "surprise"
}
]
]
with open('/Users/dsg281/Downloads/EmotionLines/Friends/friends_dev.json') as data_file:
data = json.load(data_file)
我試圖在csv
輸出“User” , “text” , “sent”列
我認為需要(改變json后有效):
file.json
[
[
{
"user": "Phoebe",
"text": "Oh my God, hes lost it. Hes totally lost it.",
"sent": "non-neutral"
},
{
"user": "Monica",
"text": "What?",
"sent": "surprise"
}
],
[{
"user": "Joey",
"text": "Hey Estelle, listen",
"sent": "neutral"
},
{
"user": "Estelle",
"text": "Well! Well! Well! Joey Tribbiani! So you came back huh? They",
"sent": "surprise"
}
]
]
import json
with open('file.json') as data_file:
data = json.load(data_file)
df = pd.concat([pd.DataFrame(x) for x in data], ignore_index=False)
print (df)
sent text user
0 non-neutral Oh my God, hes lost it. Hes totally lost it. Phoebe
1 surprise What? Monica
0 neutral Hey Estelle, listen Joey
1 surprise Well! Well! Well! Joey Tribbiani! So you came ... Estelle
然后:
df.to_csv(file, index=False)
編輯:
如果想要使用非pandas純python解決方案,可能會對此解決方案進行一點修改:
import json, csv
with open('file.json') as data_file:
data = json.load(data_file)
f = csv.writer(open("test.csv", "w+"))
f.writerow(["user", "sent", "text"])
for y in data:
for x in y: #added for read nested lists
f.writerow([x["user"], x["sent"], x["text"]])
如果我們提供空列表的起始值[]
我們可以將列表與sum
連接起來
pd.DataFrame(sum(json.load(open('file.json')), [])).to_csv('file.csv', index=False)
sent,text,user
non-neutral,"Oh my God, hes lost it. Hes totally lost it.",Phoebe
surprise,What?,Monica
neutral,"Hey Estelle, listen",Joey
surprise,Well! Well! Well! Joey Tribbiani! So you came back huh? They,Estelle
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.