How to modify a masked array in place directly by assigning to it using advanced indexing

6.7k views Asked by At

I have an array that I want to change some values on some rows. The desired rows will be addressed by a Boolean masked array. Then I want to modify one of the values in the rows:

a = np.array([[0., 0.],
              [0., 0.],
              [0., 0.],
              [0., 0.],
              [0., 0.]])
mask = np.array([False,  True,  True,  True, False])
multi = np.array([0, 1, 2], dtype=np.int64)
ind = np.array([1, 0, 1], dtype=np.int64)
res = np.array([0.02238303, 0.01624808, 0.0234094])

a[mask][multi, ind] = res
print(a)           # --> [[0. 0.] [0. 0.] [0. 0.] [0. 0.] [0. 0.]]
# The desired result --> [[0. 0.] [0. 0.02238303] [0.01624808 0.] [0. 0.0234094 ] [0. 0.]]

I know I can do this by:

sample = a[mask]
sample[multi, ind] = res
print(sample)     # --> [[0. 0.02238303] [0.01624808 0.] [0. 0.0234094]]
a[mask] = sample
print(a)          # --> [[0. 0.] [0. 0.02238303] [0.01624808 0.] [0. 0.0234094 ] [0. 0.]]

Is it possible to do this job directly by indexing on the masked array something like a[mask][multi, ind] = res? How?

0

There are 0 answers