Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy values (except 0) from array 2 to array 1

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?

like image 776
freddykrueger Avatar asked Jan 29 '18 12:01

freddykrueger


1 Answers

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.

like image 190
Tai Avatar answered Sep 18 '22 04:09

Tai