繁体   English   中英

旋转列同时保留所有其他列

[英]Pivoting column while retaining all other columns

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

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

结果 output 应该是:

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

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

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'
  )

Output:

   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
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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM