IIUC,你可以用
cumsum
并用它来掩盖领先的价值观
where
:
d = 9
a = np.array([[0, 1, 2, d],
[3, 4, d, 5],
[6, d, 7, 8]])
out = np.where(np.cumsum(a == d, axis=1), a, 0)
具有的变体
cumprod
以及就地修改:
a[np.cumprod(a!=d, axis=1).astype(bool)] = 0
输出:
array([[0, 0, 0, 9],
[0, 0, 9, 5],
[0, 9, 7, 8]])
中间掩码(对于第一种方法,考虑非零值
True
):
# np.cumsum(a == d, axis=1)
array([[0, 0, 0, 1],
[0, 0, 1, 1],
[0, 1, 1, 1]])
# np.cumprod(a!=d, axis=1).astype(bool)
array([[ True, True, True, False],
[ True, True, False, False],
[ True, False, False, False]])