Insert rows as a result of a groupby operation into the original dataframe

前端 未结 2 1947
借酒劲吻你
借酒劲吻你 2020-12-19 20:00

For example, I have a pandas dataframe as follows:

col_1   col_2   col_3  col_4
a       X        5      1
a       Y        3      2
a       Z        6      4         


        
2条回答
  •  被撕碎了的回忆
    2020-12-19 20:41

    If you can guarantee that X and Z appear only once in a group, you can use a groupby and pd.concat operation:

    new = df[df.col_2.isin(['X', 'Z'])]\
          .groupby(['col_1'], as_index=False).sum()\
          .assign(col_2='NEW')
    
    df = pd.concat([df, new]).sort_values('col_1')
    
    df
      col_1 col_2  col_3  col_4
    0     a     X      5      1
    1     a     Y      3      2
    2     a     Z      6      4
    0     a   NEW     11      5
    3     b     X      7      8
    4     b     Y      4      3
    5     b     Z      6      5
    1     b   NEW     13     13
    

提交回复
热议问题