user3763220
user3763220

Reputation: 29

How to calculate how many times values occurred in past N rows in pandas

I needed help looking for how many times value occurred in past 'n' rows. iterrrows but I can't think of how to go about it.

Below 'X' marks the values given and calculates results with n=3, so every 3rd row, it counts how many times '1' occurred in past 3 rows.

X   results (n=3)
1   1
1   2
1   3
0   2
0   1
0   0
0   0
1   1
1   2

Upvotes: 0

Views: 30

Answers (1)

BENY
BENY

Reputation: 323226

Try with rolling

df['out'] = df.X.rolling(3,min_periods=1).sum()
Out[273]: 
0    1.0
1    2.0
2    3.0
3    2.0
4    1.0
5    0.0
6    0.0
7    1.0
8    2.0
Name: X, dtype: float64

Upvotes: 1

Related Questions