2

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

This is what I tried but it returned all False:

A2[i]=image_values[updated_image_values==initial_means[i]]

Example:

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

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]]
cjds
  • 269
  • 1
  • 3
  • 12

1 Answers1

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]

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)
Divakar
  • 218,885
  • 19
  • 262
  • 358