【问题标题】:How to combine multiple rows into single row by adding columns with pandas?如何通过使用熊猫添加列将多行组合成单行?
【发布时间】:2019-04-15 10:05:21
【问题描述】:

我需要使用 pandas 将多行组合成一行,具体取决于“哈希”列

查看我的数据框:

    hash     a      b
0     1      1      6
1     1      2      7
2     1      3      8
3     2      4      9 
4     2      5      10

我希望像这样转换数据框:

   hash     a      a1     a3     b     b1     b2  
0    1      1      2      3      6     7      8   
1    2      4      5      nan    9     10     nan 

我曾尝试使用一些与 groupby 相关的代码或转置整个数据帧,但不知道该怎么做。谁能帮帮我?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    通过set_index 创建MultiIndex,通过cumcount 使用计数器列,通过unstack 重塑Multiindex 通过mapjoin 展平:

    df1 = df.set_index(['hash', df.groupby('hash').cumcount().add(1).astype(str)]).unstack()
    df1.columns = df1.columns.map(''.join)
    df1 = df1.reset_index()
    print (df1)
       hash   a1   a2   a3   b1    b2   b3
    0     1  1.0  2.0  3.0  6.0   7.0  8.0
    1     2  4.0  5.0  NaN  9.0  10.0  NaN
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-23
      • 1970-01-01
      • 2020-01-23
      • 1970-01-01
      • 2021-11-13
      • 2016-03-14
      • 2023-02-04
      • 1970-01-01
      相关资源
      最近更新 更多