Home > Back-end >  how to convert string in to different columns python
how to convert string in to different columns python

Time:06-14

I have csv file , which have one column and inside this column have string , string contains many values , i want to convert this string in muultiple columns

here is example data:

df = pd.DataFrame({'column1':[{'A':2,'B':3,'c':2}]})
print(df)
                    column1
0  {'A': 2, 'B': 3, 'c': 2}
1  {'A': 3, 'B': 5, 'c': 10}

i want output:

df = pd.DataFrame({'A':[2],'B':[3],'c':[2]})

CodePudding user response:

try this:

pd.DataFrame([*df['column1'].apply(eval)])

CodePudding user response:

First convert string that looks like dictionary to an actual dictionary

import json

my_dict = json.loads(column1)
 
# Gives you {'A': 2, 'B': 3, 'c': 2}

Then convert that dictionary to a dataframe:

pd.Dataframe([my_dict])
  • Related