我有一個名為“df”的 pandas.dataframe,格式如下:
| 團隊名字 | Positive_Sentiment | 負面情緒 |
|---|---|---|
| 第一組 | 樂于助人,大力支持 | 客戶服務緩慢,界面薄弱,管理不善 |
我想將此資料幀轉換為具有以下格式的 JSON 檔案:
[{
"Group Name": "group1",
"Postive Sentiment": [
"helpful",
"great support"
],
"Negative Sentiment": [
"slow customer service",
"weak interface",
"bad management"
]
}
]
到目前為止,我已經使用了這個:
import json
b = []
for i in range(len(df)):
x={}
x['Group Name']=df.iloc[i]['group_name']
x['Positive Sentiment']= [df.iloc[i]['Positive_Sentiment']]
x['Negative Sentiment']= [df.iloc[i]['Negative_Sentiment']]
b.append(x)
##Export
with open('AnalysisResults.json', 'w') as f:
json.dump(b, f, indent = 2)
這導致:
[{
"Group Name": "group1",
"Postive Sentiment": [
"helpful,
great support"
],
"Negative Sentiment": [
"slow customer service,
weak interface,
bad UX"
]
}
]
你可以看到它非常接近。關鍵的區別在于每一行的整個內容都用雙引號(例如,“有用,非常支持”)而不是行中的每個逗號分隔字串(例如,“有用”,“非常支持”)。我想在每個字串周圍加上雙引號。
uj5u.com熱心網友回復:
您可以申請split(",")您的專欄:
from io import StringIO
import pandas as pd
import json
inp = StringIO("""group_name Positive_Sentiment Negative_Sentiment
group1 helpful, great support slow customer service, weak interface, bad management
group2 great, good support interface meeeh, bad management""")
df = pd.read_csv(inp, sep="\s{2,}")
def split_and_strip(sentiment):
[x.strip() for x in sentiment.split(",")]
df["Positive_Sentiment"] = df["Positive_Sentiment"].apply(split_and_strip)
df["Negative_Sentiment"] = df["Negative_Sentiment"].apply(split_and_strip)
print(json.dumps(df.to_dict(orient="record"), indent=4))
# to save directly to a file:
with open("your_file.json", "w ") as f:
json.dump(df.to_dict(orient="record"), f, indent=4)
輸出:
[
{
"group_name": "group1",
"Positive_Sentiment": [
"helpful",
"great support"
],
"Negative_Sentiment": [
"slow customer service",
"weak interface",
"bad management"
]
},
{
"group_name": "group2",
"Positive_Sentiment": [
"great",
"good support"
],
"Negative_Sentiment": [
"interface meeeh",
"bad management"
]
}
]
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/349250.html
下一篇:無法獲取回呼函式回傳的所需物件
