Update by an index and a mask? Update by an index and a mask? numpy numpy

Update by an index and a mask?


A simple one with np.where with a mask as the first input to choose and assign -

mapx[idxs] = np.where(mask,mapx[idxs]+1,mapx[idxs])

Custom update values

The second argument (here mapx[idxs]+1) could be edited to any complex update that you might be doing for the masked places corresponding to True ones in mask. So, let's say you were doing an update for the masked places with :

mapx[idxs] += x * (A - mapx[idxs])

Then, replace the second arg to mapx[idxs] + x * (A - mapx[idxs]).


Another way would be to extract integer indices off True ones in mask and then create new idxs that is selective based on the mask, like so -

r,c = np.nonzero(mask)idxs_new = (idxs[0][:,0][r], idxs[1][0][c])mapx[idxs_new] += 1

The last step could be edited similarly for a custom update. Just use idxs_new in place of idxs to update.