【问题标题】:Pivoting column while retaining all other columns旋转列同时保留所有其他列
【发布时间】:2022-11-23 14:31:47
【问题描述】:

我在一个表中有很多列,但只有一列需要根据其值进行透视。它看起来像这样:

OrderNumber  Item  YearMonth  Total
1            1     2019_01    20
1            2     2019_01    40
1            1     2019_02    30
2            1     2019_02    50

结果输出应该是:

OrderNumber  Item  2019_01    2019_02   Total
1            1     60         30        20
1            2     60         30        40
1            1     60         30        30
2            1     0          50        50

基本上,在保留所有列的同时,对每个月的订单号的所有总数求和。有没有办法做到这一点?我正在使用熊猫

【问题讨论】:

  • @9769953 是的,抱歉会在

标签: python pandas


【解决方案1】:

IIUC,你需要一个pivot_table + merge

out = (df
  .merge(df.pivot_table(index='OrderNumber', columns='YearMonth',
                        values='Total', aggfunc='sum', fill_value=0),
         on='OrderNumber')
  #.drop(columns='YearMonth') # uncomment to drop unused 'YearMonth'
  )

输出:

   OrderNumber  Item YearMonth  Total  2019_01  2019_02
0            1     1   2019_01     20       60       30
1            1     2   2019_01     40       60       30
2            1     1   2019_02     30       60       30
3            2     1   2019_02     50        0       50

【讨论】:

    【解决方案2】:
    df.join(
        df.groupby(['OrderNumber', 'YearMonth'])['Total'].sum()
            .unstack(level=1,fill_value=0)
        , on='OrderNumber')
        
           OrderNumber  Item YearMonth  Total  2019_01  2019_02
        0            1     1   2019_01     20     60.0     30.0
        1            1     2   2019_01     40     60.0     30.0
        2            1     1   2019_02     30     60.0     30.0
        3            2     1   2019_02     50      0.0     50.0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-01
      • 2022-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-07
      • 2018-09-09
      • 1970-01-01
      相关资源
      最近更新 更多