下面这段简单代码在Matlab中的pythonic实现是等价的。
Matlab:
B = 2D array of integers as indices [1...100]
A = 2D array of numbers: [10x10]
A[B] = 0
其工作得很好,例如对于B[i]=42
,它找到要设置的列5
的位置2
。在Python中,它会导致错误: out of bound is logical。然而,为了将上面的Matlab代码转换成Python,我们正在寻找Python的方法。还请考虑更高维度的问题,例如:
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中的更高维度也是有效的。
发布于 2012-01-20 15:10:54
您可以在索引数组(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]])
https://stackoverflow.com/questions/8937566
复制相似问题