5

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?

0

2 Answers 2

13

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.

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

Comments

9

np.where supports this. Below solution creates a new array. For an in-place alternative, see @Tai's answer.

A = np.array(
[[1, 1, 1],
[1, 1, 1],
[1, 1, 1]])

B = np.array(
[[0, 2, 0],
[4, 0, 0],
[6, 6, 0]])

C = np.where(B==0, A, B)

# [1, 2, 1]
# [4, 1, 1]
# [6, 6, 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.