使用broadcasted-comparison 获取那些尾随的掩码,然后掩码输入 -
In [63]: r = np.arange(arr.shape[1])[::-1]
In [66]: mask = to_zero[:,None]>r
In [69]: mask # mask of trailing places to be reset in input
Out[69]:
array([[False, False, False, False],
[False, False, True, True],
[False, False, False, True],
[False, True, True, True],
[False, False, True, True]])
In [67]: arr[mask] = 0
In [68]: arr
Out[68]:
array([[ 1, 2, 15, 7],
[ 9, 11, 0, 0],
[ 5, 7, 5, 0],
[19, 0, 0, 0],
[10, 7, 0, 0]])
获取r 的替代方法是使用np.arange(arr.shape[1]-1,-1,-1)。
通过元素乘法获得最终输出的替代方法:arr*~mask。
或者用 flipped-comparison 构造 flipped-mask 然后相乘 -
In [75]: arr*(to_zero[:,None]<=np.arange(arr.shape[1]-1,-1,-1))
Out[75]:
array([[ 1, 2, 15, 7],
[ 9, 11, 0, 0],
[ 5, 7, 5, 0],
[19, 0, 0, 0],
[10, 7, 0, 0]])
对于大型阵列,利用 numexpr 的多核 -
In [78]: import numexpr as ne
In [79]: ne.evaluate('arr*mask',{'mask':to_zero[:,None]<=np.arange(arr.shape[1]-1,-1,-1)})
Out[79]:
array([[ 1, 2, 15, 7],
[ 9, 11, 0, 0],
[ 5, 7, 5, 0],
[19, 0, 0, 0],
[10, 7, 0, 0]])