user15470345
user15470345

Reputation:

Python rolling mean starting on the next row

I have results from a horse race and want to have the rolling win count for the start of each race. This is what I currently have:

Horse Position
A 4
A 1
A 3

This is what I'm after

Horse Position Wins
A 4 0
A 1 0
A 3 1

So when horse A started the second race it had 0 wins but when it started the third race is had 1 win

Upvotes: 1

Views: 196

Answers (1)

Tom McLean
Tom McLean

Reputation: 6369

Use the shift operator and cumsum

df["Wins"] = (df["Position"].shift(1) == 1).cumsum()

output:

  Horse  Position  Wins
0     A         4     0
1     A         1     0
2     A         3     1

Upvotes: 2

Related Questions