【问题标题】:Python: multidimensional array maskingPython:多维数组掩码
【发布时间】:2012-02-14 18:59:54
【问题描述】:

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 中,它会导致 error: out of bound 这是逻辑。然而,为了将上面的 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 中的更高维度也很有效。

【问题讨论】:

  • “在 Python 中它会导致错误:超出范围,这是合乎逻辑的”... 是什么原因造成的?你能展示你在 Python 中尝试过的东西吗?
  • 为什么要用一个二维数组作为另一个二维数组的索引?
  • @LaurenceGonsalves 正如问题中提到的, A.shape = (10,10) 所以按 A[42] 索引是不合法的!这不是 Matlab 代码的情况,因为它会自动将 42 匹配到第 2 行和第 4 列。
  • @FlopCoder 因为我正在翻译已经编写好的代码。我喜欢这里的 Python 逻辑 true 会导致错误。

标签: python matlab numpy multidimensional-array masking


【解决方案1】:

您可以在索引数组 (A) 之前在数组 (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]])

【讨论】:

  • 感谢您的示例。我打算请你用一个例子来展示你的解决方案,......哇!你在我发布它之前做过。有了这些例子,这个想法现在很清楚了。这两种方法都有帮助。
猜你喜欢
  • 2017-12-31
  • 2021-09-12
  • 1970-01-01
  • 1970-01-01
  • 2021-08-14
  • 2021-12-28
  • 2021-12-27
  • 1970-01-01
  • 2017-06-29
相关资源
最近更新 更多