numpy更改元素匹配条件

numpy更改元素匹配条件,numpy,Numpy,对于两个numpy数组a,b a=[1,2,3] b=[4,5,6] 我想更改x您看到的问题是遮罩如何在numpy阵列上工作的结果 当你写作时 a[a < 2.5] 是一个错误,因为b有三个元素,而a[a

对于两个numpy数组a,b

a=[1,2,3]      b=[4,5,6]

我想更改x您看到的问题是遮罩如何在numpy阵列上工作的结果

当你写作时

a[a < 2.5]
是一个错误,因为
b
有三个元素,而
a[a<2.5]
只有两个元素


在numpy中实现您所追求的结果的一个简单方法是使用
np.where

其语法为
np。其中(条件、值wheretrue、值wherefalse)

在你的情况下,你可以写

newArray = np.where(a < 2.5, b, a)
newArray=np.其中(a<2.5,b,a)

或者,如果您不想增加新阵列的开销,可以就地执行替换(正如您在问题中尝试的那样)。要实现这一点,您可以编写:

idxs = a < 2.5
a[idxs] = b[idxs]
idxs=a<2.5
a[idxs]=b[idxs]
a[a < 2.5] = b
newArray = np.where(a < 2.5, b, a)
idxs = a < 2.5
a[idxs] = b[idxs]