我有一个问题让我发疯了大约一周。我从一个称为 A 的大型形状 (2700, 1000, 3) 数组开始,然后有 2 个形状 (800, 600) 的数组,称为 B 和 C。 A 和 B 填充了感兴趣的索引更大的数组本身
A[B[i][j]][C[i][j]].shape
是一个由 3 个值组成的一维数组,例如 [0, 0, 0],其索引由 B[i][j] 和 C[i][j] 给出。现在我想将其设置为等于另一个名为 D 的形状 (800, 600) 数组。如果我使用以下方法,则可以实现此目的:
D[:] = A[B, C]
但是,我现在将 NaN 项引入 B 和 C。这意味着 A[B][C] 在遇到这种情况时会返回错误。我不能简单地执行以下操作:
B = np.where(np.logical_or(B>0, C>0), B, 0)
由于这将使 NaN 值被 0 替换,所以我最终想要的是当表示 B 或 C 的索引为 NaN 时:
D[i][j] = [0, 0, 0]
我最近的尝试是实现这样的事情:
D = np.where(np.logical_or(np.isnan(A), np.isnan(B)), self.pix[A, B], [0,0,0])
但是 NaN 索引仍在传递。抱歉,如果这篇文章解析不好,我会尽力解释。
这是我想要实现的目标的简化版本,但它还不起作用:
import numpy as np
import numpy as np
coords = np.array([[[3, 4, 2], [2, 1, np.nan]], [[2,3,2],[1, 0, 2]]])
x = np.divide(coords[0], 2)
y = np.divide(coords[1], 2)
a = np.array([1, 1, 1])
a1 = a*1
a2 = a*2
a3 = a*3
a4 = a *4
A = np.array([[a1, a2, a2, a1], [a2, a3, a3, a4], [a3, a4, a4, a1], [a3, a4, a1, a1]])
D = np.array([[a1, a2, a4], [a1, a3, a2]])
print(np.where(np.isnan(x)))
D = (np.where(x>0, A[x.astype(int), y.astype(int)], [0, 0, 0]))
最佳答案
您可以对索引数组中的 NaN 使用单独的 bool 掩码,然后使用 np.newaxis/None
使用新轴将组合掩码扩展到 3D。并将其与 np.where
-
B_nanmask = np.isnan(B)
C_nanmask = np.isnan(C)
BC_nanmask = B_nanmask | C_nanmask
# Replace NaNs with zeros to have a *valid* array w/o NaNs
B[B_nanmask] = 0
C[C_nanmask] = 0
out = np.where(BC_nanmask[...,None], 0, A[B.astype(int),C.astype(int)])
或者,分配到索引数组 -
out = A[B.astype(int),C.astype(int)]
out[BC_nanmask] = 0
如果您不想干扰索引数组,我们可以单独设置它们的整数版本 -
B_int = np.where(B_nanmask, 0, B.astype(int))
C_int = np.where(C_nanmask, 0, C.astype(int))
out = np.where(BC_nanmask[...,None], 0, A[B_int, C_int])
关于python - numpy 设置多维数组,索引数组包含 NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49639038/