0

I have a csv file, and I have put it in a pandas dataframe:

no data
1 {"age": "30", "sex": "male"}
2 {"age": "26", "sex": "female"}

I would like to create two new columns named 'age' and 'sex' (the dict. keys), then drop the original column so that it looks like this:

no age sex
1 30 male
2 26 female

How can I create those two new columns automatically using data from the dictionaries inside of the column 'data'?

manacoder
  • 31
  • 8

1 Answers1

0

We need to convert the dict like column to dict with ast

import ast
df = df.join(df.data.apply(lambda x : pd.Series(ast.literal_eval(x))))
df
Out[69]: 
   no                            data age     sex
0   1    {"age": "30", "sex": "male"}  30    male
1   2  {"age": "26", "sex": "female"}  26  female
BENY
  • 317,841
  • 20
  • 164
  • 234