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 look like this:

 [1, 2, 1] [4, 1, 1] [6, 6, 1] 

How is this possible in Python?

+5
source share
2 answers

nonzero will return the indices of an array that is not 0.

 idx_nonzero = B.nonzero() A[idx_nonzero] = B[idx_nonzero] 

nonzero also returns numpy.where when only the condition is passed. So, equivalently, we can do

 idx_nonzero = np.where(B != 0) # (B != 0).nonzero() A[idx_nonzero] = B[idx_nonzero] 

This decision is in place. If you need to create a new array, see @jp_data_analysis' .

+13
source

np.where supports this. Below the solution, a new array is created. 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] 
+9
source

Source: https://habr.com/ru/post/1275015/


All Articles