Mask 3D-array by 2D-array for slicing without for loop

Viewed 68

I have something like this

import numpy as np 

array_3D =  np.random.rand(3,3,3) 
array_2D = np.random.randint(0, 3 , (3,3)) 

for i in range(3):
    for j in range(3): 
        array_3D[:, i, j][:array_2D[i, j]]=np.nan  

Is there a way to do this without the double for loop?

1 Answers

Create the mask with outer ranged-comparison and then assign -

mask = np.less.outer(np.arange(len(array_3D)), array_2D)  
array_3D[mask] = np.nan
Related