numpy数组中的条件复制元素

时间:2019-05-09 11:23:45

标签: python arrays numpy

我想将元素从一个numpy数组复制到另一个数组,同时还要检查条件,例如如果B的元素> 1。 因此,数组A为:

array([[None, None, None],
       [None, [4, 5], None],
       [None, None, None]])

和数组B:

array([[0, 2, 2],
       [2, 2, 0],
       [0, 0, 0]])

我需要数组C

array([[None, [2], [2]],
       [[2], [2, 4, 5], None],
       [None, None, None]])

避免循环的最有效方法是什么?

1 个答案:

答案 0 :(得分:0)

使用np.where

a = np.array([None, [1,2], None])
b = np.array([0,1,2])
np.where(b>0, a, b)
>>array([None, 1, 2], dtype=object)

旁注:数组并不是那种数据的最佳选择(请参见注释)

相关问题