This is easy to understand using the method Series.shift. Since you only need to look to see if the number has crossed or not.
s = pd.Series([0,1,2,3,4,1,5,4,3,2,1])
df = pd.DataFrame({'s':s})
df['next_s'] = df.s.shift(-1)
line = 2
df
s next_s
0 0 1
1 1 2
2 2 3
3 3 4
4 4 1
5 1 5
6 5 4
7 4 3
8 3 2
9 2 1
10 1 NaN
Now you can use a simple vector conditional operator
df['cross'] = (
((df.s >= line) & (df.next_s < line)) |
((df.next_s > line) & (df.s <= line)) |
(df.s == line))
df
s next_s cross
0 0 1 False
1 1 2 False
2 2 3 True
3 3 4 False
4 4 1 True
5 1 5 True
6 5 4 False
7 4 3 False
8 3 2 False
9 2 1 True
10 1 NaN False
Now it's pretty easy to sum booleans to get the score:
df.cross.sum()
4
source
share