1

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.

1
  • Please refresh page to see an update... Commented Jul 29, 2021 at 14:52

2 Answers 2

2

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]]])
Sign up to request clarification or add additional context in comments.

2 Comments

Using a similar approach to my other answer, you could do combinied_array[combined_array==0] = new_value where new_value is whatever value you want to use in the case both a and b are 0.
Ah right, that's probably possible with np.where too but this works I think: c[np.all(b==0, axis=2)] = a[np.all(b==0, axis=2)] (same as my other answer but selecting elements where all values are 0 along the last axis)
1

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.

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.