Issue
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.
Solution
I believe the following does what you're asking:
grid[[a[second_mask] for a in np.where(mask)]] = 100
It works as follows:
np.where(mask)
converts the boolean mask into the indices wheremask
is True;[a[second_mask] for a in ...]
subsets the indices to only select those wheresecond_mask
is 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] = 100
modifying that copy rather than the original array.
Answered By - NPE
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.