Python:多维数组掩码



什么是Matlab中以下简单代码段的等效pythonic实现。

矩阵:


B = 2D array of integers as indices [1...100]
A = 2D array of numbers: [10x10]
A[B] = 0

这很有效,例如B[i]=42它找到要设置的列5的位置2。在Python中,它会导致一个错误:越界,这是合乎逻辑的。然而,为了将上面的Matlab代码翻译成Python,我们正在寻找pythonic方法。还请考虑更高维度的问题,例如:


B = 2D array of integers as indices [1...3000]
C = 3D array of numbers: [10x10x30]
C[B] = 0

我们考虑的一种方法是将索引数组元素改革为i,j而不是绝对位置。也就是说,位置42 divmod(42,m=10)[::-1] >>> (2,4).因此,我们将有一个索引的nx2 >>> ii,jj向量,可以很容易地用于索引A。我们认为这可能是一种更好的方法,对于Python中的更高维度也很有效。

您可以在索引数组 (A( 之前使用它.ravel(),然后在之后.reshape()

或者,由于您知道A.shape,因此您可以在索引之前对另一个数组 (B( 使用 np.unravel_index

示例 1:

>>> import numpy as np
>>> A = np.ones((5,5), dtype=int)
>>> B = [1, 3, 7, 23]
>>> A
array([[1, 1, 1, 1, 1],
       [1, 1, 1, 1, 1],
       [1, 1, 1, 1, 1],
       [1, 1, 1, 1, 1],
       [1, 1, 1, 1, 1]])
>>> A_ = A.ravel()
>>> A_[B] = 0
>>> A_.reshape(A.shape)
array([[1, 0, 1, 0, 1],
       [1, 1, 0, 1, 1],
       [1, 1, 1, 1, 1],
       [1, 1, 1, 1, 1],
       [1, 1, 1, 0, 1]])

示例 2:

>>> b_row, b_col = np.vstack([np.unravel_index(b, A.shape) for b in B]).T
>>> A[b_row, b_col] = 0
>>> A
array([[1, 0, 1, 0, 1],
       [1, 1, 0, 1, 1],
       [1, 1, 1, 1, 1],
       [1, 1, 1, 1, 1],
       [1, 1, 1, 0, 1]])

后来发现:您可以使用numpy.put

>>> import numpy as np
>>> A = np.ones((5,5), dtype=int)
>>> B = [1, 3, 7, 23]
>>> A.put(B, [0]*len(B))
>>> A
array([[1, 0, 1, 0, 1],
       [1, 1, 0, 1, 1],
       [1, 1, 1, 1, 1],
       [1, 1, 1, 1, 1],
       [1, 1, 1, 0, 1]])

最新更新