【问题标题】:Transform multiple row to column in Pandas在 Pandas 中将多行转换为列
【发布时间】:2021-05-31 03:27:53
【问题描述】:

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

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)

【问题讨论】:

    标签: python pandas numpy row transform


    【解决方案1】:
    (
        df.groupby('userid')
        .account.apply(lambda x: x.tolist())
        .apply(pd.Series)
        .rename(columns=lambda x: f'account {int(x)+1}')
        .reset_index()
    )
    

    【讨论】:

      【解决方案2】:

      您可以使用groupby.cumcountpivot 创建标题列:

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-07-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-17
        • 2023-03-02
        • 1970-01-01
        相关资源
        最近更新 更多