如何使用3D数组和2D数组numpy进行遮罩 [英] How to mask with 3d array and 2d array numpy
问题描述
如何使用1d数组从3d数组中选择一组元素.
How do you select a group of elements from a 3d array using a 1d array.
#These are my 3 data types
# A = numpy.ndarray[numpy.ndarray[float]]
# B1 = numpy.ndarray[numpy.ndarray[numpy.ndarray[float]]]
#B2=numpy.ndarray[numpy.ndarray[numpy.ndarray[float]]]
#I want to choose values from A based on values from B1 in the B2
这是我尝试过的,但返回了所有False
:
This is what I tried but it returned all False
:
A2[i]=image_values[updated_image_values==initial_means[i]]
示例:
A=[[1,1,1][2,2,2]]
B=[[[1,1,1],[2,3,4]],[[2,2,2],[1,1,1]],[[1,1,1],[2,2,2]]]
B2=[[[2,2,2],[9,3,21]],[[22,0,-2],[-1,-1,1]],[[1,-1,-1],[10,0,2]]]
#A2 is calculated as the means of the B2 values that correspond
#to it's value according to B
因此,要计算A2
,我们使用B2中的哪些值等于A中的值.因此,对于第一个索引A[0]
,B[0][0]
,B[1][1]
和B[2][0]
等于A2[0]
,我们在B2
中获得相应的B
值,并使用这些值计算每个索引的平均值:
So, to calculate A2
we use check what values in B2 are equal to values in A. So, for the first index A[0]
, B[0][0]
,B[1][1]
and B[2][0]
are equal to A[0]
. So for A2[0]
, we get the corresponding values of B
in B2
and use those to calculate the average for each index:
#A2[0][0]=(B2[0][0][0]+B2[1][1][0]+B2[2][0][0]) /3 = 0.67
#A2[1][2]=(B2[1][0][2]+B2[2][1][2]) /2 = 0
#After doing this for every A2 value, A2 should be:
A2=[[0.67,0,0.67],[16,0,0]]
推荐答案
Here's a vectorized approach with np.add.reduceat
-
idx = np.argwhere((B == A[:,None,None]).all(-1))
B2_indexed = B2[idx[:,1],idx[:,2]]
_,start, count = np.unique(idx[:,0],return_index=1,return_counts=1)
out = np.add.reduceat(B2_indexed,start)/count.astype(float)[:,None]
或者,我们可以避免使用3D
掩码创建4D
掩码,而不是获取idx
,这样可以节省一些内存,就像这样-
Alternatively, we can save on memory a bit by avoiding creating 4D
mask with a 3D
mask instead for getting idx
, like so -
dims = np.maximum(B.max(axis=(0,1)),A.max(0))+1
A_reduced = np.ravel_multi_index(A.T,dims)
B_reduced = np.ravel_multi_index(B.T,dims)
idx = np.argwhere(B_reduced.T == A_reduced[:,None,None])
这是使用单循环的另一种方法-
Here's another approach with one-loop -
out = np.empty(A.shape)
for i in range(A.shape[0]):
r,c = np.where((B == A[i]).all(-1))
out[i] = B2[r,c].mean(0)
这篇关于如何使用3D数组和2D数组numpy进行遮罩的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!