You can use groupby/cumcount to assign column numbers and then call pivot :
import pandas as pd df = pd.DataFrame({'x': [0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2], 'y': [1, 1, 2, 5, 6, 8, 1, 8, 4, 1, 7, 3]}) df['columns'] = df.groupby('x')['y'].cumcount()
gives
y columns 0 1 2 3 x 0 1 5 1 1 1 1 6 8 7 2 2 8 4 3
Or, if you can really rely on values ββin x repeating in order N times,
N = 3 result = pd.DataFrame(df['y'].values.reshape(-1, N).T)
gives
0 1 2 3 0 1 5 1 1 1 1 6 8 7 2 2 8 4 3
Using reshape is faster than calling groupby/cumcount and pivot , but it is less reliable because it relies on the values ββin y appearing in the correct order.
source share