【问题标题】:Collapsing rows折叠行
【发布时间】:2022-11-02 23:50:19
【问题描述】:

我有下表:

我想根据 ID 和日期折叠 Code_1 和 Code_2 列。根据我在网上找到的内容,我尝试了下面的 sn-p 代码,但它似乎不起作用。

df= df.groupby(['ID','Date']).agg(''.join)

东风:

ID Date Code_1 Code_2
A1 2022-02-02 AAAA 0
A1 2022-02-02 0 BBBB
A1 2022-03-14 AAAA 0
C1 2022-04-20 0 BBBB
C1 2022-04-20 AAAA 0

期望的输出:

ID Date Code_1 Code_2
A1 2022-02-02 AAAA BBBB
A1 2022-03-14 AAAA 0
C1 2022-04-20 AAAA BBBB

【问题讨论】:

    标签: python pandas


    【解决方案1】:
    # groupby and take the group's max
    df.groupby(['ID','Date'], as_index=False).max() 
    
        ID  Date       Code_1   Code_2
    0   A1  2022-02-02  AAAA    BBBB
    1   A1  2022-03-14  AAAA    0
    2   C1  2022-04-20  AAAA    BBBB
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-25
      • 2021-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-22
      • 2016-10-26
      • 2015-08-08
      相关资源
      最近更新 更多