I have the following code which first selects elements of a NumPy array with a logical index mask:
import numpy as np
grid = np.random.rand(4,4)
mask = grid > 0.5
I wish to use a second boolean mask against this one to pick out objects with :
masklength = len(grid[mask])
prob = 0.5
# generates an random array of bools
second_mask = np.random.rand(masklength) < prob
# this fails to act on original object
grid[mask][second_mask] = 100
This is not quite the same problem as listed in this SO question:
Numpy array, how to select indices satisfying multiple conditions? – as I am using random number generation, I don’t want to have to generate a full mask, only for the elements selected by the first mask.
I believe the following does what you’re asking:
It works as follows:
np.where(mask)converts the boolean mask into the indices wheremaskis True;[a[second_mask] for a in ...]subsets the indices to only select those wheresecond_maskis True.The reason your original version doesn’t work is that
grid[mask]involves fancy indexing. This creates a copy of the data, which in turn results in...[second_mask] = 100modifying that copy rather than the original array.