How to re-arrange this df in groups of 3

Question:

I have a shortened version of my real data in which I would like to re-arrange as described below.

Input:

import pandas as pd
import numpy as np  
data4 = [[45], [285], [256], [55], [360], [213], [65], [435], [368]]
df4 = pd.DataFrame(data4)

Output:

     0
0   45
1  285
2  256
3   55
4  360
5  213
6   65
7  435
8  368
    

Desired Output:

    0    1    2
0  45  285  256
1  55  360  213
2  65  435  368
Asked By: user9106985

||

Answers:

With np.reshape: pd.DataFrame(df4.values.reshape(-1, 3))

Answered By: jogepari

With pivot() :

df4["count"] = df4.index%3
df4.pivot(index=None, columns="count", values=0).bfill().iloc[::3, :].reset_index(drop=True)
Answered By: Benjamin Rio
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.