1

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])
1
  • 1
    Won't x[mask] = [30,40] work? Commented Jun 10, 2016 at 18:12

1 Answer 1

2

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])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.