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