在pandas中如何计算'Countif'在移动window的基础上?

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

给出

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])

假设您想滚动计算最近 3 个观察值中 C 列中 < 0 的观察值数量。在 excel 中,您可以根据条件在指定的 window 上滑动 'countif' 计算,所需的结果将是:

D = # of x < 0 on a rolling window basis of size 3

A
Out[79]: 
   A  B  C  D
1  1  5 -2  
2  2  4 -4
3  3  3 -1  3
4  4  2  2  2
5  5  1  4  1

如何使用 Pandas 以高效的(Pythonic)方式做到这一点?

谢谢

您可以在布尔值列上使用 rolling_sum

>>> 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

这是有效的,因为 True ~ 1 和 False ~ 0,我们有

>>> A["C"] < 0
1     True
2     True
3     True
4    False
5    False
Name: C, dtype: bool