JavaSa
JavaSa

Reputation: 6241

Pandas -unpacking several values to another columns and merging to one single Df out of it

Consider you have the following raw df:

   A                      B                  
0  {'hello':'world'}   {'covid':19}          
1  {'hello':'moon'}    {'covid':23}          

And I want to have a result df like:

       hello            covid        
0      world              19            
1      moon               23

How do I achieve this using pandas?

If I do:

x = raw_df.A.dropna().apply(pd.Series)  
y = raw_df.B.dropna().apply(pd.Series)

I will get part of the result df , some in x and some in y.

  1. How do I concatenate them in their matching indexes to be the result df I mentioned above?
  2. Can I write one line to have it all? (unpack relevant columns dicts values and merge them back)

Upvotes: 2

Views: 55

Answers (2)

Quang Hoang
Quang Hoang

Reputation: 150745

You can try:

pd.concat((pd.DataFrame.from_records(x) for x in df.values.T), axis=1)

Output:

   hello  covid
0  world     19
1   moon     23

Upvotes: 1

BENY
BENY

Reputation: 323276

We can do stack and unstack

s=df.stack().apply(pd.Series).stack().reset_index(level=1,drop=True).unstack()
   hello covid
0  world    19
1   moon    23

Upvotes: 1

Related Questions