[英]How to Split a comma separated string of dictionaries into a Pandas dataframe
I have a string in this format: 我有以下格式的字符串:
{apple:"34253453",oranges:"Sweet",x:"COOL"},{apple:"34222453",oranges:"Dry",x:"WARM"},{apple:"31113453",oranges:"Bitter",x:"HOT"},{apple:"38883453",oranges:"Sweet",x:"COOL"}
And looking to create a dataframe with the column labels as 'apple','oranges','x' and the values placed in their respective rows. 并希望创建一个数据框,其列标签为“ apple”,“ oranges”,“ x”,并将值放置在它们各自的行中。
I've tried to use this solution: Python convert comma separated list to pandas dataframe as well as ast.literal_eval to convert it into a list before transforming it into a dataframe but to no luck. 我尝试使用此解决方案: Python将逗号分隔的列表转换为熊猫数据框,以及将ast.literal_eval转换为列表,然后再将其转换为数据框,但没有运气。
Your string is invalid json
, so necessary some replace first: 您的字符串是无效的
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.