查找pandas.Series中的值何时越过/达到阈值

joa*_*oao 4 python pandas

请考虑以下系列

s = pd.Series([0,1,2,3,4,1,5,4,3,2,1])
Run Code Online (Sandbox Code Playgroud)

有没有一种简单的方法可以知道达到/超过2值的次数(没有明显的迭代解决方案)?

上述示例的预期结果应为4(2行在系列中向上或向下划线4次).

编辑:更新的示例案例

fir*_*ynx 7

这与容易acheiveable Series.shift方法.因为您只需要向前看一个以了解数字是否已经越过.

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
Run Code Online (Sandbox Code Playgroud)

现在您可以使用简单的可向量化条件语句

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
Run Code Online (Sandbox Code Playgroud)

现在很容易总结布尔值来计算:

df.cross.sum()
4
Run Code Online (Sandbox Code Playgroud)