How to calculate differences between consecutive rows in pandas data frame?

前端 未结 2 1636
一个人的身影
一个人的身影 2020-12-06 01:26

I\'ve got a data frame, df, with three columns: count_a, count_b and date; the counts are floats, and the dates are conse

相关标签:
2条回答
  • 2020-12-06 01:58

    You can using the .rolling_apply(…) method:

    diffs_a = pd.rolling_apply(df['count_a'], 2, lambda x: x[0] - x[1])
    

    Alternatively, if it's easier, you can operate on the arrays directly:

    count_a_vals = df['count_a'].values
    diffs_a = count_a_vals[:-1] - count_a_vals[1:]
    
    0 讨论(0)
  • 2020-12-06 02:01

    diff should give the desired result:

    >>> df.diff()
    count_a  count_b
    2015-01-01      NaN      NaN
    2015-01-02    38465      NaN
    2015-01-03    36714      NaN
    2015-01-04    35137      NaN
    2015-01-05    35864      NaN
    ....
    2015-02-07   142390    25552
    2015-02-08   126768    22835
    2015-02-09   122324    21485
    
    0 讨论(0)
提交回复
热议问题