布尔值序列的累积视图实现:寻求更高效的替代方案
更高效的累积布尔序列处理方法
针对你需要将布尔序列转换为「首次出现True后始终保持True」的累积视图需求,有几个比cumsum+np.where更简洁高效的方案:
1. NumPy 原生累积逻辑或
直接使用np.logical_or.accumulate(),专门适配布尔数组的累积或操作,一步到位:
import numpy as np arr = np.array([False, False, True, False, True, False]) result = np.logical_or.accumulate(arr) # 输出: array([False, False, True, True, True, True])
2. NumPy 累积最大值
布尔值在NumPy中会被隐式视为0(False)和1(True),用np.maximum.accumulate()也能直接得到目标结果,性能和上述方法相当:
result = np.maximum.accumulate(arr)
3. Pandas Series 累积最大值
如果你的数据是Pandas Series,直接调用cummax()方法即可,无需额外类型转换:
import pandas as pd s = pd.Series([False, False, True, False, True, False]) result = s.cummax() # 输出: # 0 False # 1 False # 2 True # 3 True # 4 True # 5 True # dtype: bool
这些方法都省去了数值转换和二次判断的额外开销,不仅代码更简洁,性能也更优——其中logical_or.accumulate()完全贴合布尔序列的操作场景,可读性和效率都拉满。
内容的提问来源于stack exchange,提问作者jumpenjack
相关产品推荐
相关产品推荐

