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.
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.
Your string is invalid json
, so necessary some replace first:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.