numpy更改元素匹配条件 [英] numpy change elements matching conditions

查看:169
本文介绍了numpy更改元素匹配条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于两个 numpy 数组 a, b

For two numpy array a, b

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

我想将 a 的 x<2.5 数据更改为 b.所以我尝试了

I want to change x<2.5 data of a to b. So I tried

a[a<2.5]=b

希望 a 成为 a=[4,5,3].但这会出错

hoping a to be a=[4,5,3]. but this makes error

Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    a[a<2.5]=b
ValueError: NumPy boolean array indexing assignment cannot assign 3 input values to the 2 output values where the mask is true

有什么问题?

推荐答案

您看到的问题是由于掩码在 numpy 数组上的工作方式造成的.

The issue you're seeing is a result of how masks work on numpy arrays.

写作时

a[a < 2.5]

你得到与掩码 a < 匹配的 a 元素2.5.在这种情况下,这将仅是前两个元素.

you get back the elements of a which match the mask a < 2.5. In this case, that will be the first two elements only.

正在尝试

a[a < 2.5] = b

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

is an error because b has three elements, but a[a < 2.5] has only two.

在 numpy 中实现您想要的结果的一种简单方法是使用 np.where.

An easy way to achieve the result you're after in numpy is to use np.where.

它的语法是np.where(condition, valuesWhereTrue, valuesWhereFalse).

在你的情况下,你可以写

In your case, you could write

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

<小时>

或者,如果您不想要新数组的开销,您可以就地执行替换(正如您在问题中尝试做的那样).为此,您可以编写:


Alternatively, if you don't want the overhead of a new array, you could perform the replacement in-place (as you're trying to do in the question). To achieve this, you can write:

idxs = a < 2.5
a[idxs] = b[idxs]

这篇关于numpy更改元素匹配条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆