
使用 NumPy 的 np.logical_or.accumulate() 或 np.maximum.accumulate() 沿列方向(axis=1)累积逻辑或/最大值,可高效实现“首次 True 出现后,该行后续所有元素置为 True(或 1)”的前向填充效果。
使用 numpy 的 np.logical_or.accumulate() 或 np.maximum.accumulate() 沿列方向(axis=1)累积逻辑或/最大值,可高效实现“首次 true 出现后,该行后续所有元素置为 true(或 1)”的前向填充效果。
在数据预处理、掩码扩展或信号触发建模等场景中,常需对布尔矩阵执行“前向传播填充”:即对每一行,从左到右扫描,一旦遇到首个 True(或 1),则将其右侧(含自身)所有位置统一设为 True。这种操作本质是行内累积逻辑“或”——因为 False or False = False,而一旦出现 True,后续所有 True or anything = True。
NumPy 提供了高度优化的向量化方案,无需 Python 循环:
import numpy as np
A = np.array([
[0, 0, 0, 0, 1, 0, 1],
[0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]
]).astype(bool)
# ✅ 推荐:直接对布尔数组累积逻辑或(返回布尔型结果)
result_bool = np.logical_or.accumulate(A, axis=1)
print("布尔结果:")
print(result_bool)
# ✅ 若需整数类型(0/1),可先转 int 再用 maximum.accumulate
result_int = np.maximum.accumulate(A.astype(int), axis=1)
print("\n整数结果:")
print(result_int)
输出为:
布尔结果: [[False False False False True True True] [False False False False False False True] [ True True True True True True True] [False False False False False False False]] 整数结果: [[0 0 0 0 1 1 1] [0 0 0 0 0 0 1] [1 1 1 1 1 1 1] [0 0 0 0 0 0 0]]
⚠️ 注意事项:
-
axis=1表示沿列方向累积(即每行独立处理),切勿误用axis=0(那将沿行方向累积,效果完全不同); -
np.logical_or.accumulate()天然适配布尔数组,性能最优且语义清晰;np.maximum.accumulate()更通用(支持整数/浮点),当输入含非 0/1 值时行为不同,但在此类二值场景下结果一致; - 该操作是纯函数式、无副作用的,原始数组
A不会被修改; - 对于大规模矩阵,此方法比逐行
np.where+np.arange手动索引快一个数量级以上。
总结:np.logical_or.accumulate(A, axis=1) 是解决“行内首次 True 后全填充”问题最简洁、高效、可读性强的标准 NumPy 范式。










