Numpy - replacing value in array based on a condition on a coordinate vector representing one dimension

Viewed 113

I have a data array of multiple dimensions, with the last one being the distance. On the other hand, I have the distance vector r. For instance:

Data = np.ones((20, 30, 100))
r = np.linspace(10, 50, 100)

Finally, I also have a list of critical distance values called r0, such that (r0.shape == Data.shape[:-1]).all(). For instance,

r0 = np.random.random((20, 30))*40 + 10

I'm looking to replace values of Data by zero based on a condition on r and r0 corresponding to the first dimensions of Data. For example, I want for any i and j that:

Data[i, j, r>=r0[i,j]] = 0 

Consider that Data can be a big array such that using loops is very long. My current workaround is:

r_temp = np.broadcast_to(np.expand_dims(r, list(np.arange(len(Data.shape)-1))), Data.shape)
Data[r_temp >= r0[..., None]] = 0

It is fast, but it consumes a lot of memory considering that I have to store the array r_temp, which can be problematic if Data starts to be big.

Any solution that does not necessitate to create and store r_temp ?

Note: for the creation of r_temp, see here.

0 Answers
Related