1 回答

TA貢獻1824條經驗 獲得超6個贊
我相信,您離想要的格式不遠了。唯一的問題是列forth包含字典作為字符串。一種可能的方法是將所有內容轉換回字典,使用 eval 將字符串轉換回字典,并使用 json 解析器很好地打印它:
import pandas as pd
import json
data = {'First': ['First value', 'Second value'],
'Second': ['First value', 'Second value'],
'third': ['First value', 'Second value'],
'forth': ['[{"values": "","entity": "datetime","Turn": [{"expression": "","tid": "","type": "", "value": "","mod": "","anchor": "","beginPoint": "","endPoint": ""}]}]','[{"values": "","entity": "datetime","Turn": [{"expression": "","tid": "","type": "", "value": "","mod": "","anchor": "","beginPoint": "","endPoint": ""}]}]'],
}
df = pd.DataFrame (data, columns = ['First','Second','third','forth'])
my_dict = df.to_dict(orient='records')
for row in my_dict:
row['forth'] = eval(row['forth'])
my_json = json.dumps(my_dict, indent=2)
print(my_json)
有兩個小的更正,密鑰大寫Second和無效條目:, "", 在您的forth密鑰中。
這是我的輸出的副本:
[
{
"First": "First value",
"Second": "First value",
"third": "First value",
"forth": [
{
"values": "",
"entity": "datetime",
"Turn": [
{
"expression": "",
"tid": "",
"type": "",
"value": "",
"mod": "",
"anchor": "",
"beginPoint": "",
"endPoint": ""
}
]
}
]
}, ...
如果列forth已經是數據框中的字典,您可以to_json直接調用,格式將是您想要的。例如,您可以嘗試將更正后的數據轉換回my_dict數據幀:
test_df = pd.DataFrame(my_dict)
print(test_df.to_json(orient='records', indent=2))
添加回答
舉報