Home > Back-end >  Pandas Series Split Value into Columns
Pandas Series Split Value into Columns

Time:11-13

I have a series that looks like this:

index
1     [{'id':1, 'primary':True,'source':None},{'id':2,'primary':False,'source':email}]
2     [{'id':2234, 'primary':True,'source':None},{'id':234,'primary':False,'source':email}]   
3     [{'id':32, 'primary':False,'source':None}]

I want this to be a dataframe that looks like this:

index     id     primary     source
1         1      True        None
1         2      False       email
2         2234   True        None
2         234    False       email
3         32     False       google

I tried running this:

df_phone_numbers = df_phone_numbers.drop("phone_numbers", axis =1).join(pd.DataFrame(df_phone_numbers["phone_numbers"].to_dict()).T)

But I get an error message "All arrays must be of the same length"

Any advice?

CodePudding user response:

Try convert the exploded series:

k = s.explode()
pd.DataFrame(k.tolist(), k.index)

Output:

     id  primary source
1     1     True   None
1     2    False  email
2  2234     True   None
2   234    False  email
3    32    False   None
  • Related