将多行转换为 Pandas 中的列

Transform multiple row to column in Pandas

我有这个数据。我想将行转换为列。我尝试了以下查询:

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

我希望结果是这样的:

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

我试过这个查询,但它不起作用

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

您可以使用 groupby.cumcount 创建 header 列,然后 pivot:

df['cols'] = 'account ' + df.groupby('userid').cumcount().add(1).astype(str)
df
#   userid  account       cols
#0       1      123  account 1
#1       1      456  account 2
#2       2      789  account 1
#3       2      123  account 2
#4       2      467  account 3

df.pivot(index='userid', columns='cols', values='account').reset_index()

#cols  userid  account 1  account 2  account 3
#0          1      123.0      456.0        NaN
#1          2      789.0      123.0      467.0
(
    df.groupby('userid')
    .account.apply(lambda x: x.tolist())
    .apply(pd.Series)
    .rename(columns=lambda x: f'account {int(x)+1}')
    .reset_index()
)