我不明白numpy.take,雖然它似乎是我想要的功能。我有一個 ndarray,我想使用另一個 ndarray 來索引第一個。
import numpy as np
# Create a matrix
A = np.arange(75).reshape((5,5,3))
# Create the index array
idx = np.array([[1, 0, 0, 1, 1],
[1, 1, 0, 1, 1],
[1, 0, 1, 0, 1],
[1, 1, 0, 0, 0],
[1, 1, 1, 1, 0]])
鑒于上述情況,我想A按idx. 我想take這樣做,但它沒有輸出我所期望的。
# Index the 3rd dimension of the A matrix by the idx array.
Asub = np.take(A, idx)
print(f'Value in A at 1,1,1 is {A[1,1,1]}')
print(f'Desired index from idx {idx[1,1]}')
print(f'Value in Asub at [1,1,1] {Asub[1,1]} <- thought this would be 19')
我期待在 idx 位置看到值之一,該值A基于idx:
Value in A at 1,1,1 is 19
Desired index from idx 1
Value in Asub at [1,1,1] 1 <- thought this would be 19
uj5u.com熱心網友回復:
一種可能性是創建broadcast具有第三維一的行和列索引,即與 (5,5) idx 配對的 (5,1) 和 (5,):
In [132]: A[np.arange(5)[:,None],np.arange(5), idx]
Out[132]:
array([[ 1, 3, 6, 10, 13],
[16, 19, 21, 25, 28],
[31, 33, 37, 39, 43],
[46, 49, 51, 54, 57],
[61, 64, 67, 70, 72]])
這最終會從A[:,:,0]和中選擇值A[:,:,1]。這將 的值idx作為整數,在有效 (0,1,2) 的范圍內(對于形狀 3)。它們不是布爾選擇器。
Out[132][1,1]為 19,與A[1,1,1]; Out[132][1,2]是一樣的A[1,2,0]。
take_along_axis獲得相同的值,但增加了維度:
In [142]: np.take_along_axis(A, idx[:,:,None], 2).shape
Out[142]: (5, 5, 1)
In [143]: np.take_along_axis(A, idx[:,:,None], 2)[:,:,0]
Out[143]:
array([[ 1, 3, 6, 10, 13],
[16, 19, 21, 25, 28],
[31, 33, 37, 39, 43],
[46, 49, 51, 54, 57],
[61, 64, 67, 70, 72]])
迭代等價物可能更容易理解:
In [145]: np.array([[A[i,j,idx[i,j]] for j in range(5)] for i in range(5)])
Out[145]:
array([[ 1, 3, 6, 10, 13],
[16, 19, 21, 25, 28],
[31, 33, 37, 39, 43],
[46, 49, 51, 54, 57],
[61, 64, 67, 70, 72]])
如果您無法以“矢量化”陣列方式表達動作,請繼續撰寫集成版本。它將避免很多歧義和誤解。
獲得相同值的另一種方法是將idx值視為 True/False 布林值:
In [146]: np.where(idx, A[:,:,1], A[:,:,0])
Out[146]:
array([[ 1, 3, 6, 10, 13],
[16, 19, 21, 25, 28],
[31, 33, 37, 39, 43],
[46, 49, 51, 54, 57],
[61, 64, 67, 70, 72]])
uj5u.com熱心網友回復:
IIUC,您可以通過廣播 idx 陣列來獲得結果陣列,使其形狀與A被乘以相同,然后索引以獲取1列為:
Asub = (A * idx[:, :, None])[:, :, 1] # --> Asub[1, 1] = 19
# [[ 1 0 0 10 13]
# [16 19 0 25 28]
# [31 0 37 0 43]
# [46 49 0 0 0]
# [61 64 67 70 0]]
我認為這是最快的方式(或最好的方式之一),特別是對于大型陣列。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/485471.html
