简体   繁体   中英

Numpy copy non-zero elements from one array to another (3D array)

my question is if there is an easy way to copy non zero values from one numpy 3d array to another. I wouldn't like to create 3 for loops for that...

Let's say I have an array a:

a = np.array([ [ [1,2,3], [4,5,6]],[[7,8,9], [10,11,12] ] ])
# to visualize it better:
# a = np.array([
#   [  
#     [1,2,3], 
#     [4,5,6]
#   ], 
#   [ 
#     [7,8,9], 
#     [10,11,12] 
#   ] 
# ])
#

then there is an array b:

b = np.array([ [[3,0,9], [0,0,0]], [[0,0,0], [45,46,47]] ])
# to visualize it better:
# b = np.array([
#   [  
#     [3,0,9], 
#     [0,0,0]
#   ], 
#   [ 
#     [0,0,0], 
#     [45,46,47] 
#   ] 
# ])
#

And I would like to merge those arrays to receive non-zero elements from b and other elements from a (these elements that are 0s in b) SO the output would look like:


# 
# np.array([
#   [  
#     [3,2,9], 
#     [4,5,6]
#   ], 
#   [ 
#     [7,8,9], 
#     [45,46,47] 
#   ] 
# ])
#

It doesn't have to be numpy, it can be openCV, but still I would like to know how to achieve this.

You can try using np.where to select from b with the condition b!=0 , or else to select from a :

combined_array = np.where(b!=0, b, a)

>>> combined_array
array([[[ 3,  2,  9],
        [ 4,  5,  6]],

       [[ 7,  8,  9],
        [45, 46, 47]]])

This should do it:

import numpy as np

a = np.array([ [ [1,2,3], [4,5,6]],[[7,8,9], [10,11,12] ] ])
b = np.array([ [[3,0,9], [0,0,0]], [[0,0,0], [45,46,47]] ])

c = b.copy()
c[b==0] = a[b==0]
print(c)

#[[[ 3  2  9]
#  [ 4  5  6]]
#
# [[ 7  8  9]
#  [45 46 47]]]

Where b==0 is an array with the same shape as b where the elements are True if the corresponding element in b equals 0 and False otherwise. You can then use that to select the zero elements of b and replace them with the values at those indices in a .

Edit: The other answer with np.where is nicer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM