How To Mask With 3d Array And 2d Array Numpy
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[num
Solution 1:
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))+1A_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 inrange(A.shape[0]):
r,c = np.where((B == A[i]).all(-1))
out[i] = B2[r,c].mean(0)
Post a Comment for "How To Mask With 3d Array And 2d Array Numpy"