Python 快速替换数组中特定值的方法

Python fast way to substitute specific values in array

假设我有两个 numpy 数组

a = np.array([[1,2,3],[4,5,6],[7,8,9]])
b = np.array([2,7,6])

我想获得

c = np.array([[1,0,3],[4,5,0][0,8,9]])

也就是说,我想用值 0 替换数组 a 中其值包含在序列 b 中的所有元素。 最快最干净的方法吗? (有没有类似substitute(a,b,0)

c = a.copy()
for num in b:
    c[c == num] = 0

备选答案:

c = a.copy()
c[np.in1d(a.ravel(), b).reshape(a.shape)] = 0

np.in1d 有点像 "in" 运算符的矢量化版本,但它仅适用于一维数组。 (因此进行了 ravel 和 reshape 操作。)