Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy replace matrix elementwise with another matrix

Tags:

python

numpy

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?

like image 674
curiouscupcake Avatar asked Mar 24 '26 03:03

curiouscupcake


2 Answers

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.

like image 168
a_guest Avatar answered Mar 26 '26 16:03

a_guest


You can use np.where:

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

array([[1, 2],
       [2, 1]])
​
like image 30
yatu Avatar answered Mar 26 '26 17:03

yatu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!