Home > Mobile >  Reordering DataFrame in Pandas
Reordering DataFrame in Pandas

Time:12-13

I have a DataFrame that looks like this:

   A   B   C   D   E
1  a   a   a   a   a
2  b   b   b   b   b
3  c   c   c   c   c
4  d   d   d   d   d
5  e   e   e   e   e
6  f   f   f   f   f 

Anyone knows how to reorder it using Pandas to make it look like this:

   A   B   C   D   E   F   G   H   I   J
1  a   a   a   a   a   b   b   b   b   b
3  c   c   c   c   c   d   d   d   d   d
5  e   e   e   e   e   f   f   f   f   f

I tried reading the documentation https://pandas.pydata.org/docs/user_guide/reshaping.html. Its difficult to understand as a beginner, appreciate any help.

CodePudding user response:

Assuming that you want to group every two rows in a single row, use the underlying numpy array and reshape it:

from string import ascii_uppercase

out = (pd.DataFrame(df.to_numpy().reshape(len(df)//2, -1),
                    index=df.index[::2])
         .rename(columns=dict(enumerate(ascii_uppercase)))
       )

Output:

   A  B  C  D  E  F  G  H  I  J
1  a  a  a  a  a  b  b  b  b  b
3  c  c  c  c  c  d  d  d  d  d
5  e  e  e  e  e  f  f  f  f  f
  • Related