簡體   English   中英

關於 numpy "at" 函數索引的問題

[英]A question about numpy "at" function indexation

我正在嘗試使用庫來計算相轉移熵。 長話短說,它一直拋出索引越界異常,我隔離了一段代碼,它看起來很像這樣:

import numpy as np 

idx1 = np.array([7, 6, 6, 6, 5, 5, 5, 6, 7, 5, 5, 7, 8, 5, 5, 5, 8, 4, 6, 7, 7, 8, 6, 7, 5, 6, 5, 4, 5, 6, 6, 7, 7, 6, 6, 6, 5, 6, 7, 7, 6, 7, 7, 7, 5, 6, 8, 6])
idx2 = np.array([7, 7, 7, 6, 6, 5, 5, 6, 7, 5, 5, 7, 9, 6, 4, 5, 8, 4, 6, 7, 6, 8, 6, 7, 5, 6, 4, 5, 6, 5, 5, 7, 6, 5, 6, 5, 6, 6, 7, 7, 6, 7, 8, 7, 5, 6, 8, 6])

arr = np.zeros([idx1.max()+1, idx2.max()+1])
arr_via_for = np.zeros([idx1.max()+1, idx2.max()+1])

for i, j in zip(idx1, idx2):
    arr_via_for[i, j] += 1
    
np.add.at(arr, [idx1, idx2], 1)

我期望的是 arr 和 arr_via_for 應該完全相同,但它們顯然不是,這條線

np.add.at(arr, [idx1, idx2], 1)

拋出異常“IndexError:索引 9 超出尺寸為 9 的軸 0 的范圍”,我無法找出原因。 感覺就像我遺漏了一些關於索引的非常明顯的東西,但我到底做錯了什么?

hpaulj 是對的(感謝您的幫助)。 在多維第一個操作數的情況下,“at”函數需要數組元組而不是數組數組。 我變了

np.add.at(arr, [idx1, idx2], 1)

np.add.at(arr, (idx1, idx2), 1)

現在它工作正常,並且 arr 和 arr_via_for 是相等的。 我沒有檢查它,但我想原因是“array-of-arrays”索引更早工作(正如 FBruzzesi 在 1.19.1 numpy 的評論中提到的那樣)並且現在不工作(至少對於 1.23.5)。 我正在使用的庫是 4 年前編寫的,所以我只是稍微更改一下它的代碼,希望它能正常工作。

在大多數編程語言中,數組對象的索引都是從 0 開始,以對象的大小減 1結束。 在 Python 中,錯誤或消息或警告指出某些數組或向量的大小以大小n結尾,但實際上您可以通過 LIST[( n - 1)] 訪問列表的最后一項。

>>> list_ = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> 
>>> # Size of the list
>>> len(list)
9
>>> list_[0]
1
>>> list_[1]
2
>>> list_[8]
9
>>> list_[9]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

與您的numpy對象相同。 array_[(array_.index("last-item"))] != array_[(len(array_))]

arr = np.array([2,3,4])
np.add.at(arr, [0,1,1,2], 1)
print(arr)
Output:
[3 5 4]

在我的例子中,第二個參數 [0,1,1,2] 不能有數字 3,因為 arr 變量中沒有可用的索引 3。

上面的示例將根據索引號將數字加 1。

暫無
暫無

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

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