将矩阵的一部分覆盖在另一个矩阵的顶部

Nin*_*zAI 5 python numpy image

我有两个 numpy 数组 - 基本上是 SimpleCV 图像的 numpy 表示。其中一个矩阵包含的条目大部分为零,但少数条目除外。我想将这些非零条目复制到另一个矩阵。我可以使用简单的循环轻松完成此操作for,但出于清晰度和性能原因,我想使用 numpy 来完成此操作。阅读文档后,似乎屏蔽数组是可行的方法,但我无法弄清楚如何告诉 numpy 仅复制非屏蔽条目。一个虚拟示例:

x = np.array([1,2,31,32,4,0,3,0,0,0])
y = np.ma.masked_where(x == 0, x)
z = np.array([99] * len(x))

z[:] = y
Run Code Online (Sandbox Code Playgroud)

我希望y仅更新 中的非屏蔽条目z,但会执行普通副本。我现在的方向正确吗,还是应该去别处寻找?

mgi*_*son 4

您只需使用 3 个参数形式即可np.where

>>> import numpy as np
>>> x = np.array([1,2,31,32,4,0,3,0,0,0])
>>> z = np.array([99] * len(x))
>>> y = np.where(x != 0, x, z)
>>> y
array([ 1,  2, 31, 32,  4, 99,  3, 99, 99, 99])
Run Code Online (Sandbox Code Playgroud)

  • 我知道你只是从OP复制它,但是 `z = ...` 行是不必要的,因为 `where` 将广播:`y = np.where(x!=0, x, 99)` (2认同)