Calculating difference between two rows in Python / Pandas

前端 未结 3 1185
不知归路
不知归路 2020-11-30 01:19

In python, how can I reference previous row and calculate something against it? Specifically, I am working with dataframes in pandas - I have a da

3条回答
  •  被撕碎了的回忆
    2020-11-30 01:32

    To calculate difference of one column. Here is what you can do.

    df=
          A      B
    0     10     56
    1     45     48
    2     26     48
    3     32     65
    

    We want to compute row difference in A only and want to consider the rows which are less than 15.

    df['A_dif'] = df['A'].diff()
    df=
              A      B      A_dif
        0     10     56      Nan
        1     45     48      35
        2     26     48      19
        3     32     65      6
    df = df[df['A_dif']<15]
    
    df=
              A      B      A_dif
        0     10     56      Nan
        3     32     65      6
    

提交回复
热议问题