Search code examples
pythonpandasnumpyrowtransform

Transform multiple row to column in Pandas


i have this data. I would like to transform the rows to column. I have try the query below:

userid account
001     123
001     456
002     789
002     123
002     467

i would like the result to be like this:

userid  account 1  account 2   account 3
001      123         456         null
002      789         123         467

i have tried this query,but it doesn't work

df = df.set_index(['userid'])['account'].unstack()
print (df)

Solution

  • (
        df.groupby('userid')
        .account.apply(lambda x: x.tolist())
        .apply(pd.Series)
        .rename(columns=lambda x: f'account {int(x)+1}')
        .reset_index()
    )