簡體   English   中英

numpy.where()子句錯誤

[英]numpy.where() clause error

簡單來說...這是問題所在:

import numpy as np
a = np.array([ 0, 1, 2, 3, 4, 5, 6, 100, 8, 9])
np.where(a==100, -1, a[a])

我期望得到的是: 0, 1, 2, 3, 4, 5, 6, -1, 8, 9 -1、8、9相反,我得到的是: index 100 out of bounds 0<=index<10

我承認該索引無效,但據我了解numpy.where()命令結構,它不應該等於a [100]而是改為-1。

在此示例中我做錯了什么?

只是為了澄清我實際上在這里試圖做的是更詳細的代碼:這是一個查找表數組的重新映射過程:

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)

用作函數參數的表達式在傳遞給函數之前將被求值( 文檔鏈接 )。 因此,即使在np.where之前,您也會從表達式a[a]中獲得索引錯誤。

使用以下內容:

np.where(a==100, -1, a)

文檔所述

numpy.where(condition[, x, y])

Return elements, either from x or y, depending on condition.
If only condition is given, return condition.nonzero().

在這里, a==100是您的條件,滿足條件時應采用的值為-1True ), a是要a的值。


出現IndexError的原因是您的a[a] :您要對數組a本身進行索引,這等效於a[[0,1,2,3,4,5,6,100,8,9]] :失敗,因為a元素少於100個...


另一種方法是:

a_copy = a.copy()
a_copy[a==100] = -1

(如果要更改a_copya替換)

當您編寫a[a]您嘗試從a獲取索引0,1,2 ... 100 ...,這就是為什么使索引超出范圍錯誤。 您應該改寫np.where(a==100, -1, a) -我認為這將產生您想要的結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM