'How to combine rows to change the shape of a pandas dataframe

I would like to rearrange a dataframe so that every 2 rows are combined into one row.
For example

0  a  b  c  d
1  e  f  g  h
2  i  j  k  l
3  m  n  o  p 

into:

0  a  b  c  d  e  f  g  h
1  i  j  k  l  m  n  o  p

I need to do this for quite a large table of data and have been unable to find a solution. I'm a complete python novice and would appreciate any help. Thanks



Solution 1:[1]

You can use the underlying numpy array and numpy's reshape method:

df2 = pd.DataFrame(df.to_numpy().reshape((len(df)//2, -1)))

output:

   0  1  2  3  4  5  6  7
0  a  b  c  d  e  f  g  h
1  i  j  k  l  m  n  o  p
alternatively using pandas:
pd.concat([df.iloc[::2].reset_index(drop=True),
           df.iloc[1::2].reset_index(drop=True)],
           axis=1)

but you will have duplicated column names:

   0  1  2  3  0  1  2  3
0  a  b  c  d  e  f  g  h
1  i  j  k  l  m  n  o  p

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mozway