[英]How to Split a comma separated string of dictionaries into a Pandas dataframe
我有以下格式的字符串:
{apple:"34253453",oranges:"Sweet",x:"COOL"},{apple:"34222453",oranges:"Dry",x:"WARM"},{apple:"31113453",oranges:"Bitter",x:"HOT"},{apple:"38883453",oranges:"Sweet",x:"COOL"}
並希望創建一個數據框,其列標簽為“ apple”,“ oranges”,“ x”,並將值放置在它們各自的行中。
我嘗試使用此解決方案: Python將逗號分隔的列表轉換為熊貓數據框,以及將ast.literal_eval轉換為列表,然后再將其轉換為數據框,但沒有運氣。
您的字符串是無效的json
,因此有必要先進行替換:
import ast
s = '{apple:"34253453",oranges:"Sweet",x:"COOL"},{apple:"34222453",oranges:"Dry",x:"WARM"},{apple:"31113453",oranges:"Bitter",x:"HOT"},{apple:"38883453",oranges:"Sweet",x:"COOL"}'
ss = '[' + s.replace('{', '{"').replace(':"','":"').replace('",', '","') + ']'
print (ss)
[{"apple":"34253453","oranges":"Sweet","x":"COOL"},
{"apple":"34222453","oranges":"Dry","x":"WARM"},
{"apple":"31113453","oranges":"Bitter","x":"HOT"},
{"apple":"38883453","oranges":"Sweet","x":"COOL"}]
df = pd.DataFrame(ast.literal_eval(ss))
print (df)
apple oranges x
0 34253453 Sweet COOL
1 34222453 Dry WARM
2 31113453 Bitter HOT
3 38883453 Sweet COOL
df = pd.DataFrame(pd.io.json.loads(ss))
print (df)
apple oranges x
0 34253453 Sweet COOL
1 34222453 Dry WARM
2 31113453 Bitter HOT
3 38883453 Sweet COOL
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.