How to convert a column of dtype object containing key and value pairs, to a new data frame

cc = dataframe.orders

0    {'S0': 50.806451612903224, 'S2': 37.8681626928...
Name: orders, dtype: object

I have a column name orders in my df and I want to create a new data frame from that of this structure

S0 S1 S2
50 37 33

Can someone suggest what should be the code for this in python

Submitted May 05th 2021 by Admin


Try literal_eval to convert to dict and apply to get Series then convert to int with astype:

import ast import pandas as pd df = pd.DataFrame({'orders': [ "{'S0': 50.806451612903224, 'S1': 37.86816269, 'S2': 33.2341234}"
]}) df = df.orders.apply(lambda x: pd.Series(ast.literal_eval(x))).astype(int) print(df.to_string(index=False))
 S0 S1 S2 50 37 33

Admin | 4 months ago


Another option is to just pass cc to the DataFrame constructor after parsing the strings as dicts:

from ast import literal_eval pd.DataFrame(*cc.apply(literal_eval))

Admin | 4 months ago

Relevant Questions