a1234
a1234

Reputation: 821

Pandas parse json column and and keep existing column into a new dataframe

I have the following dataframe:

name  stats
smith {"eye_color": "brown", "height": 160, "weight": 76}
jones {"eye_color": "blue", "height": 170, "weight": 85}
will  {"eye_color": "green", "height": 180, "weight": 94}

I use the following code to parse the json field into a new dataframe:

new_df = df["stats"].apply(json.loads).apply(pd.Series)

This gives me new_df:

eye_color height weight
brown     160    76
blue      170    85
green     180    94

How can I update the code the above to add name to new_df, so that I have:

name  eye_color height weight
smith brown     160    76
jones blue      170    85
will  green     180    94

Upvotes: 1

Views: 107

Answers (1)

anky
anky

Reputation: 75080

Use df.join():

new_df=df[['name']].join(df["stats"].apply(json.loads).apply(pd.Series))

Upvotes: 2

Related Questions