Inserting new rows in pandas data frame at specific indices

前端 未结 2 981
名媛妹妹
名媛妹妹 2020-12-09 20:12

I have a following data frame df with two columns \"identifier\", \"values\" and \"subid\":

     identifier   values    subid
0      1              


        
2条回答
  •  有刺的猬
    2020-12-09 21:07

    subtract where the prior row is different than the current row

    # edit in place
    df['values'] -= df.identifier.ne(df.identifier.shift().bfill())
    df
    
        identifier  values
    0            1     101
    1            1     102
    2            1     103
    3            1     104
    4            1     105
    5            2     105
    6            2     107
    7            2     108
    8            2     109
    9            2     110
    10           3     110
    11           3     112
    12           3     113
    

    Or

    # new dataframe
    df.assign(values=df['values'] - df.identifier.ne(df.identifier.shift().bfill()))
    
        identifier  values
    0            1     101
    1            1     102
    2            1     103
    3            1     104
    4            1     105
    5            2     105
    6            2     107
    7            2     108
    8            2     109
    9            2     110
    10           3     110
    11           3     112
    12           3     113
    

提交回复
热议问题