Reordering DataFrame in Pandas

Question:

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.

Asked By: Henul

||

Answers:

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
Answered By: mozway
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.