C_Z_
C_Z_

Reputation: 7806

Write to a masked array in numpy

Let's say I have an array x and a mask for the array mask. I want to use np.copyto to write to x using mask. Is there a way I can do this? Just trying to use copyto doesn't work, I suppose because the masked x is not writeable.

x = np.array([1,2,3,4])
mask = np.array([False,False,True,True])

np.copyto(x[mask],[30,40])

x
# array([1, 2, 3, 4])
# Should be array([1, 2, 30, 40])

Upvotes: 1

Views: 179

Answers (1)

hpaulj
hpaulj

Reputation: 231510

As commented index assignment works

In [16]: x[mask]=[30,40]

In [17]: x
Out[17]: array([ 1,  2, 30, 40])

You have to careful when using x[mask]. That is 'advanced indexing', so it creates a copy, not a view of x. With direct assignment that isn't an issue, but with copyto x[mask] is passed as an argument to the function.

In [19]: y=x[mask]
In [21]: np.copyto(y,[2,3])

changes y, but not x.

Checking its docs I see the copyto does accept a where parameter, which could be used as

In [24]: np.copyto(x,[0,0,31,41],where=mask)

In [25]: x
Out[25]: array([ 1,  2, 31, 41])

Upvotes: 2

Related Questions