0

What I have as dataframe using python3.

     A  B    C  D  E
0  foo  0  1.2  1  2
1  foo  1  1.3  2  4
2  foo  2  2.1  2  5
3  foo  3  3.1  3  5
4  nan  0    0  0  0
5  bar  0  4.1  4  6
6  bar  1  1.2  5  8
7  bar  2  1.4  6  9
8  bar  3  5.0  7  9

What I would like to reshape it to

        0             1               2               3
     A    C  D  E       C  D  E         C  D  E         C  D  E
0  foo  1.2  1  2     1.3  2  4       2.1  2  5       3.1  3  5
1  bar  4.1  4  6     1.2  5  8       1.4  6  9       5.0  7  9

So far I have tried examples from this post but it create aggregate of values and I am not successful in just reshaping. Any help would be appreciated.

stack
  • 51
  • 4

1 Answers1

1

We can try unstack after set_index, then trim the index with sort_index + swaplevel

out = df.dropna().set_index(['A','B']).unstack().sort_index(level=1,axis=1).swaplevel(0,1,axis=1).reset_index()
Out[62]: 
B    A    0          1          2          3      
          C  D  E    C  D  E    C  D  E    C  D  E
0  bar  4.1  4  6  1.2  5  8  1.4  6  9  5.0  7  9
1  foo  1.2  1  2  1.3  2  4  2.1  2  5  3.1  3  5
BENY
  • 317,841
  • 20
  • 164
  • 234