In pandas how to calculate 'Countif' on a moving window basis?

前端 未结 1 1492
情深已故
情深已故 2021-01-19 13:15

Given

A = pd.DataFrame([[1, 5, -2], [2, 4, -4], [3, 3, -1], [4, 2, 2], [5, 1, 4]],
             columns=[\'A\', \'B\', \'C\'], index=[1, 2, 3, 4, 5])
         


        
相关标签:
1条回答
  • 2021-01-19 14:08

    You can use rolling_sum on a column of bools:

    >>> A["D"] = pd.rolling_sum((A["C"] < 0), 3)
    >>> A
       A  B  C   D
    1  1  5 -2 NaN
    2  2  4 -4 NaN
    3  3  3 -1   3
    4  4  2  2   2
    5  5  1  4   1
    

    This works because True ~ 1 and False ~ 0, and we have

    >>> A["C"] < 0
    1     True
    2     True
    3     True
    4    False
    5    False
    Name: C, dtype: bool
    
    0 讨论(0)
提交回复
热议问题