Dev*_*per 2 python matlab numpy masking multidimensional-array
什么是Matlab中以下简单代码的等效pythonic实现.
Matlab的:
B = 2D array of integers as indices [1...100]
A = 2D array of numbers: [10x10]
A[B] = 0
Run Code Online (Sandbox Code Playgroud)
这样可以很好地工作,例如B[i]=42它找到要设置2的列的位置5.在Python中它会导致错误:超出界限是合乎逻辑的.然而,为了将上述Matlab代码翻译成Python,我们正在寻找pythonic方法.还请考虑更高尺寸的问题,例如:
B = 2D array of integers as indices [1...3000]
C = 3D array of numbers: [10x10x30]
C[B] = 0
Run Code Online (Sandbox Code Playgroud)
我们考虑的一种方法是改进索引数组元素i,j而不是绝对位置.也就是说,定位42到divmod(42,m=10)[::-1] >>> (2,4).所以我们将有一个nx2 >>> ii,jj索引向量,可以A很容易地用于索引.我们认为这可能是一种更好的方法,对于Python中的更高维度也是有效的.
您可以.ravel()在索引之前使用数组(A),然后再使用它.reshape().
或者,因为您知道A.shape,您可以np.unravel_index在索引之前使用其他数组(B).
例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]])
Run Code Online (Sandbox Code Playgroud)
例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]])
Run Code Online (Sandbox Code Playgroud)
稍后发现:你可以使用 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]])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
859 次 |
| 最近记录: |