3

I have the following df whose values are dictionaries:

                    tests
SO4  {'Mon': 6, 'Tues': 6, 'Wed': 7}
CH3  {'Mon': 0, 'Tues': 8, 'Wed': 10}

I would like to obtain the desired output :

         0        1          2
SO4  'Mon': 6 'Tues': 6 'Wed': 7
CH3  'Mon': 0 'Tues': 8 'Wed': 10

How could I split the dictionary into individual columns?

I have seen the columns split of strings using rsplit function but not sure on how to apply it in the case of dictionaries as values.

Zero
  • 74,117
  • 18
  • 147
  • 154
JamesHudson81
  • 2,215
  • 4
  • 23
  • 42

1 Answers1

8

I think better is use:

df = pd.DataFrame(df['tests'].values.tolist(), index=df.index)
print (df)
     Mon  Tues  Wed
SO4    6     6    7
CH3    0     8   10

But if really need it (but dicts are by design not sortable, so maybe get different output):

df = df['tests'].astype(str).str.strip('{}').str.split(', ', expand=True)
print (df)
            0          1          2
SO4  'Mon': 6   'Wed': 7  'Tues': 6
CH3  'Mon': 0  'Wed': 10  'Tues': 8
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252