I have 2 numpy arrays with the same shape. Now I want to copy all values, except 0, from array 2 to array 1.
array 1:
[1, 1, 1]
[1, 1, 1]
[1, 1, 1]
array 2:
[0, 2, 0]
[4, 0, 0]
[6, 6, 0]
The result should now look like this:
[1, 2, 1]
[4, 1, 1]
[6, 6, 1]
How is this possible in Python?
nonzero
will return the indices of an array that is not 0.
idx_nonzero = B.nonzero()
A[idx_nonzero] = B[idx_nonzero]
nonzero
is also what numpy.where
returns when only a condition is passed in. Thus, equivalently, we can do
idx_nonzero = np.where(B != 0) # (B != 0).nonzero()
A[idx_nonzero] = B[idx_nonzero]
This solution is in-place. If you need to create a new array, see @jp_data_analysis' answer.
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