Reputation: 175
I have a dataframe with two columns, the second column has values as dictionary. I'm trying to convert the key of the dictionary into separate columns of the dataframe.
df
name values
a {'king':'diamond','queen':'spade','jack':'club'}
a {'king':'spade','queen':'club','jack':'diamond'}
b {'king':'club','queen':'diamond','jack':'spade'}
b {'king':'spade','queen':'spade','jack':'diamond'}
Expected Output
df
name king queen jack
a diamond spade club
a spade club diamond
b club diamond spade
b spade spade diamond
I was thinking of using pandas.DataFrame()
but not sure how it would be applied to a column in a dataframe. What should be the approach?
Thanks!
Upvotes: 0
Views: 282
Reputation: 8302
You can also do,
print(df.set_index("name")['value'].apply(pd.Series).reset_index())
name king queen jack
0 a diamond spade club
1 a spade club diamond
2 b club diamond spade
3 b spade spade diamond
Upvotes: 1
Reputation: 12523
Use the following:
pd.concat([df, pd.DataFrame(list(df["values"]))], axis=1)
The result is:
name values king queen \
0 a {'king': 'diamond', 'queen': 'spade', 'jack': ... diamond spade
1 a {'king': 'spade', 'queen': 'club', 'jack': 'di... spade club
2 b {'king': 'club', 'queen': 'diamond', 'jack': '... club diamond
3 b {'king': 'spade', 'queen': 'spade', 'jack': 'd... spade spade
jack
0 club
1 diamond
2 spade
3 diamond
Upvotes: 0