简体   繁体   English

Numpy 将非零元素从一个数组复制到另一个(3D 数组)

[英]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.我的问题是是否有一种简单的方法可以将非零值从一个 numpy 3d 数组复制到另一个。 I wouldn't like to create 3 for loops for that...我不想为此创建 3 个 for 循环......

Let's say I have an array a:假设我有一个数组 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:

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:我想合并这些数组以接收来自 b 的非零元素和来自 a 的其他元素(这些元素在 b 中为 0)所以输出看起来像:


# 
# 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.它不必是 numpy,它可以是 openCV,但我仍然想知道如何实现这一点。

You can try using np.where to select from b with the condition b!=0 , or else to select from a :您可以尝试使用np.whereb选择条件b!=0 ,或者从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.其中b==0是一个与b具有相同形状的数组,其中如果b中的相应元素等于 0,则元素为 True,否则为 False。 You can then use that to select the zero elements of b and replace them with the values at those indices in a .然后,您可以用它来选择的零个元素b和在这些指数中,值替换它们a

Edit: The other answer with np.where is nicer.编辑: np.where的另一个答案更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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