1

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.

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.