2

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?

Divakar
  • 218,885
  • 19
  • 262
  • 358
clearseplex
  • 679
  • 1
  • 7
  • 22

1 Answers1

1

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