Skip to main content
 首页 » 编程设计

python之Numpy 或 pandas : test whether upper or lower bound is reached in array/series, 并且首先到达

2024年10月17日33qq号

我有一个 pandas 系列。

我需要检查是否达到了系列的下限或上限。

如果同时达到下限和上限,我需要知道先达到哪个。

我可以使用 .max() 和 .min() 函数来确定是否达到了边界之一:

def upper_bound_reached(series, upper_bound): 
    return series.max() >= upper_bound 
 
def lower_bound_reached(series, lower_bound): 
    return series.min() <= lower_bound 

我遇到的问题是先达到哪个

if upper_bound_reached(series, ub) and lower_bound_reached(series, lb): 
    # work out which bound is reached first 

实现此目标最惯用的方法是什么?

一些图表显示了我正在寻找的内容:

未达到界限 - 返回 NONE:


仅达到上限 - 返回 UPPER:


两个边界都已达到,首先是下限 - 返回 LOWER:


请您参考如下方法:

s = pd.Series(np.sin(np.arange(0, 7, .1))) 
upper_bound = 0.5 
lower_bound = -0.5 
 
filtered = s[(s >= upper_bound) | (s <= lower_bound)] 
 
first_crossing = None 
if not filtered.empty: 
    first_crossing = 'UPPER' if filtered.index[0] >= upper_bound else 'LOWER' 
 
>>> first_crossing 
'UPPER'