Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reshape a multi-column dataframe by index?

Following from here . The solution works for only one column. How to improve the solution for multiple columns. i.e If I have a dataframe like

df= pd.DataFrame([['a','b'],['b','c'],['c','z'],['d','b']],index=[0,0,1,1])
   0  1
0  a  b
0  b  c
1  c  z
1  d  b

How to reshape them like

  0   1  2  3
0  a  b  b  c 
1  c  z  d  b

If df is

   0  1
0  a  b
1  c  z
1  d  b

Then

   0  1   2  3
0  a  b NaN  NaN
1  c  z   d  b

like image 952
Bharath Avatar asked Dec 14 '25 17:12

Bharath


1 Answers

Use flatten/ravel

In [4401]: df.groupby(level=0).apply(lambda x: pd.Series(x.values.flatten()))
Out[4401]:
   0  1  2  3
0  a  b  b  c
1  c  z  d  b

Or, stack

In [4413]: df.groupby(level=0).apply(lambda x: pd.Series(x.stack().values))
Out[4413]:
   0  1  2  3
0  a  b  b  c
1  c  z  d  b

Also, with unequal indices

In [4435]: df.groupby(level=0).apply(lambda x: x.values.ravel()).apply(pd.Series)
Out[4435]:
   0  1    2    3
0  a  b  NaN  NaN
1  c  z    d    b
like image 154
Zero Avatar answered Dec 16 '25 19:12

Zero



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!