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?
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.
You can use np.where:
np.where(a!=0, a, b)
array([[1, 2],
[2, 1]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With