在一个轴上查找 3D 数组中的最小值,并将另一个 3D 数组中的非对应值替换为 0,在 python 中没有循环
Finding min values in a 3D array across one axis and replacing the non-corresponding values in another 3D array with 0 without loops in python
假设我们有两个 3D 数组,A(x,y,z) 和 B(x,y,z),其中 x,y,z 是维度。我想识别 A 数组中 z 轴上的所有最小值,然后根据这些值及其索引选择 B 中的相应值,保留它们并将其他值替换为零。
你可以换个角度想。在 A
中找到最小值的位置很简单:
ind = np.expand_dims(np.argmin(A, axis=2), axis=2)
您可以执行以下操作之一:
最简单:创建 B
的替换并填充相关元素:
C = np.zeros_like(B)
np.put_along_axis(C, ind, np.take_along_axis(B, ind, 2), 2)
同样的事情,但是 in-place:
values = np.take_along_axis(B, ind, 2)
B[:] = 0
np.put_along_axis(B, ind, values, 2)
将索引转换为掩码:
mask = np.ones(B.shape, dtype=bool)
np.put_along_axis(mask, ind, False, 2)
B[mask] = 0
您可以用合适的索引表达式替换对 take_along_axis
和 put_along_axis
的调用。特别是:
indx, indy = np.indices(A.shape[:-1])
indz = np.argmin(A, axis=-1)
上面的例子就变成了
新数组:
C = np.zeros_like(B)
C[indx, indy, indz] = B[indx, indy, indz]
In-place:
values = B[indx, indy, indz]
B[:] = 0
B[indx, indy, indz] = values
屏蔽:
mask = np.ones(B.shape, dtype=bool)
mask[indx, indy, indz] = False
B[mask] = 0
假设我们有两个 3D 数组,A(x,y,z) 和 B(x,y,z),其中 x,y,z 是维度。我想识别 A 数组中 z 轴上的所有最小值,然后根据这些值及其索引选择 B 中的相应值,保留它们并将其他值替换为零。
你可以换个角度想。在 A
中找到最小值的位置很简单:
ind = np.expand_dims(np.argmin(A, axis=2), axis=2)
您可以执行以下操作之一:
最简单:创建
B
的替换并填充相关元素:C = np.zeros_like(B) np.put_along_axis(C, ind, np.take_along_axis(B, ind, 2), 2)
同样的事情,但是 in-place:
values = np.take_along_axis(B, ind, 2) B[:] = 0 np.put_along_axis(B, ind, values, 2)
将索引转换为掩码:
mask = np.ones(B.shape, dtype=bool) np.put_along_axis(mask, ind, False, 2) B[mask] = 0
您可以用合适的索引表达式替换对 take_along_axis
和 put_along_axis
的调用。特别是:
indx, indy = np.indices(A.shape[:-1])
indz = np.argmin(A, axis=-1)
上面的例子就变成了
新数组:
C = np.zeros_like(B) C[indx, indy, indz] = B[indx, indy, indz]
In-place:
values = B[indx, indy, indz] B[:] = 0 B[indx, indy, indz] = values
屏蔽:
mask = np.ones(B.shape, dtype=bool) mask[indx, indy, indz] = False B[mask] = 0