How To Expand A Df By Different Dict As Columns?
I have a df with different dicts as entries in a column, in my case column 'information'. I would like to expand the df by all possible dict.keys(), something like that: import pan
Solution 1:
Another approach would be using pandas.DataFrame.from_records
:
import pandas as pd
new = pd.DataFrame.from_records(df.pop('information').apply(lambda x: {} if pd.isna(x) else x))
new = pd.concat([df, new], 1)
print(new)
Output:
cost id name amount color shape
011 banana NaN yellow curve
122 apple NaN red NaN223 orange NaNNaNround3104 strawberry 500.0NaNNaN445 toast NaNNaNNaN
Solution 2:
You can use:
d ={k:{}if v != v else v for k, v in df.pop('information').items()}
df1 = pd.DataFrame.from_dict(d, orient='index')
df = pd.concat([df, df1], axis=1)
print(df)
id name cost shape color amount
01 banana 1 curve yellow NaN12 apple 2NaN red NaN23 orange 2roundNaNNaN34 strawberry 10NaNNaN500.045 toast 4NaNNaNNaN
Post a Comment for "How To Expand A Df By Different Dict As Columns?"