2

I have an n * x numpy matrix, which could look like this:

a = np.array([[1, 0], [0, 1]])

and I have another n * n numpy matrix, which look like this:

b = np.array([[2, 2], [2, 2]])

I would like to replace zero elements of a with the corresponding element of b so I would get:

[[1, 2],
 [2, 1]]

How can I do that?

2 Answers 2

4

You can just use a boolean mask:

mask = (a == 0)
a[mask] = b[mask]

This is efficient if you want to update the original array a since it only assigns to the zero elements, not the whole array.

Sign up to request clarification or add additional context in comments.

4 Comments

I think numpy.where is the elegant way to do it
@ansev The question asked for replacing elements in an array, not computing a new array. Using numpy.where for that task is going to be inefficient if only a few number of elements are zero as it needs to assign the whole array back to a.
On a test (1000,1000) array, this answer is 3-4x faster than the where. np.copyto with a where parameter is a bit faster than this, np.copyto(a, b, where=a==0) . Exact time advantages may very with the proportion of 0s in a.
@hpaulj This makes sense since the masking solution needs to loop over the mask twice and creates a temporary object for the r.h.s while np.copyto can loop all parts together and doesn't need a temporary array. Very good!
4

You can use np.where:

np.where(a!=0, a, b)

array([[1, 2],
       [2, 1]])
​

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.