How Can I Create Column From Dictionary Keys In Same Dataframe?
I have a dataframe, something like: | | a | b | |---|---|------------------| | 0 | a | {'d': 1, 'e': 2} | | 1 | b | {'d': 3, 'e': 4} | | 2 | c | NaN |
Solution 1:
You can try the following:
>>> df
a b
0 a {'d': 1, 'e': 2}
1 b {'d': 3, 'e': 4}
2 c NaN
3 d {'f': 5}
>>> df.join(pd.DataFrame.from_records(df['b'].mask(df.b.isna(), {}).tolist()))
a b d e f
0 a {'d': 1, 'e': 2} 1.0 2.0 NaN
1 b {'d': 3, 'e': 4} 3.0 4.0 NaN
2 c NaN NaN NaN NaN
3 d {'f': 5} NaN NaN 5.0
Solution 2:
Replace NaN with None and then proceed
df = pd.DataFrame({'a':['a','b','c','d'],
'b':[{'d': 1, 'e': 2},
{'d': 3, 'e': 4},
np.nan,
{'f': 5}]
})
df = df.where(pd.notnull(df), None)
pd.concat([df, df['b'].apply(pd.Series)], axis=1)
Output:
a b d e f
0 a {'d':1,'e':2}1.02.0NaN1 b {'d':3,'e':4}3.04.0NaN2c None NaNNaNNaN3 d {'f':5}NaNNaN5.0
Post a Comment for "How Can I Create Column From Dictionary Keys In Same Dataframe?"