[英]numpy.where() clause error
Briefly... here is the problem: 简单来说...这是问题所在:
import numpy as np
a = np.array([ 0, 1, 2, 3, 4, 5, 6, 100, 8, 9])
np.where(a==100, -1, a[a])
What I expect to get is: 0, 1, 2, 3, 4, 5, 6, -1, 8, 9
Instead I'm getting: index 100 out of bounds 0<=index<10
我期望得到的是:
0, 1, 2, 3, 4, 5, 6, -1, 8, 9
-1、8、9相反,我得到的是: index 100 out of bounds 0<=index<10
I admit that the index is invalid but is shouldn't eval a[100] but -1 instead... as far as I understand numpy.where() command structure. 我承认该索引无效,但据我了解numpy.where()命令结构,它不应该等于a [100]而是改为-1。
What I'm doing wrong in this example? 在此示例中我做错了什么?
Just to clarify what I actually trying to do here is more detailed code: It is a lookup table array remapping procedure: 只是为了澄清我实际上在这里试图做的是更详细的代码:这是一个查找表数组的重新映射过程:
import numpy as np
# gamma-ed look-up table array
lut = np.power(np.linspace(0, 1, 32), 1/2.44)*255.0
def gamma(x):
ln = (len(lut)-1)
idx = np.uint8(x*ln)
frac = x*ln - idx
return np.where( frac == 0.0,
lut[idx],
lut[idx]+(lut[idx+1]-lut[idx])*frac)
# some linear values array to remap
lin = np.linspace(0, 1, 64)
# final look-up remap
gamma_lin = gamma(lin)
Expressions that you put as function arguments are evaluated before they are passed to the function ( Documentation link ). 用作函数参数的表达式在传递给函数之前将被求值( 文档链接 )。 Thus you are getting an index error from the expression
a[a]
even before np.where
is called. 因此,即使在
np.where
之前,您也会从表达式a[a]
中获得索引错误。
Use the following: 使用以下内容:
np.where(a==100, -1, a)
As stated by the documentation : 如文档所述 :
numpy.where(condition[, x, y])
Return elements, either from x or y, depending on condition.
If only condition is given, return condition.nonzero().
Here, a==100
is your condition, -1
the value that should be taken when the condition is met ( True
), a
the values to fall back on. 在这里,
a==100
是您的条件,满足条件时应采用的值为-1
( True
), a
是要a
的值。
The reason why you're getting an IndexError is your a[a]
: you're indexing the array a
by itself, which is then equivalent to a[[0,1,2,3,4,5,6,100,8,9]]
: that fails because a
has less than 100 elements... 出现IndexError的原因是您的
a[a]
:您要对数组a
本身进行索引,这等效于a[[0,1,2,3,4,5,6,100,8,9]]
:失败,因为a
元素少于100个...
Another approach is: 另一种方法是:
a_copy = a.copy()
a_copy[a==100] = -1
(replace a_copy
by a
if you want to change it in place) (如果要更改
a_copy
用a
替换)
When you write a[a]
you try to take index 0,1,2...100... from a
which is why you get the index out of bounds error. 当您编写
a[a]
您尝试从a
获取索引0,1,2 ... 100 ...,这就是为什么使索引超出范围错误。 You should instead write np.where(a==100, -1, a)
- I think that will produce the result you are looking for. 您应该改写
np.where(a==100, -1, a)
-我认为这将产生您想要的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.