Unpack dictionary from Pandas Column
Solution 1:
Setup
df = pd.DataFrame(dict(
codes=[
{'amount': 12, 'code': 'a'},
{'amount': 19, 'code': 'x'},
{'amount': 37, 'code': 'm'},
np.nan,
np.nan,
np.nan,
]
))
df
codes
0 {'amount': 12, 'code': 'a'}
1 {'amount': 19, 'code': 'x'}
2 {'amount': 37, 'code': 'm'}
3 NaN
4 NaN
5 NaN
apply
with pd.Series
Make sure to dropna
first
df.codes.dropna().apply(pd.Series)
amount code
0 12 a
1 19 x
2 37 m
df.drop('codes', 1).assign(**df.codes.dropna().apply(pd.Series))
amount code
0 12.0 a
1 19.0 x
2 37.0 m
3 NaN NaN
4 NaN NaN
5 NaN NaN
tolist
and from_records
Same idea but skip the apply
pd.DataFrame.from_records(df.codes.dropna().tolist())
amount code
0 12 a
1 19 x
2 37 m
df.drop('codes', 1).assign(**pd.DataFrame.from_records(df.codes.dropna().tolist()))
amount code
0 12.0 a
1 19.0 x
2 37.0 m
3 NaN NaN
4 NaN NaN
5 NaN NaN
Solution 2:
Setup
codes
0 {'amount': 12, 'code': 10}
1 {'amount': 3, 'code': 3}
apply
with pd.Series
df.codes.apply(pd.Series)
amount code
0 12 10
1 3 3