首页 > 解决方案 > 如果数组中的值匹配条件,则用另一个数组中相同位置的值替换数组中的值的最快方法

问题描述

我正在尝试使用此语法将数组中的值替换为另一个数组中相同位置的值(如果它们匹配条件):

array[array>limit]=other_array[array>limit]

它有效,但我想我可能会很难做到。有什么想法吗?

标签: pythonarraysnumpyindexingreplace

解决方案


使用np.where

参数

条件:array_like,布尔

   Where True, yield x, otherwise yield y.

x,y:array_like

   Values from which to choose. x, y and condition need to be broadcastable to some shape.

退货

出:ndarray

   An array with elements from x where condition is True, and elements from y elsewhere.

例子:

a1 = np.array([3, 2, 4, 1])
a2 = a1 + 10

limit = 2
>>> np.where(a1 > limit, a2, a1)
array([13,  2, 14,  1])

推荐阅读