[英]Indexing NumPy 2D array with another 2D array
我有類似的東西
m = array([[1, 2],
[4, 5],
[7, 8],
[6, 2]])
和
select = array([0,1,0,0])
我的目標是
result = array([1, 5, 7, 6])
我在Simplfy row AND column提取 numpy 中閱讀時嘗試了_ix ,但這並沒有得到我想要的結果。
ps 如果你能想到更精確的問題,請更改這個問題的標題。
這樣做的numpy方法是使用np.choose
或花哨的 indexing/take(見下文):
m = array([[1, 2],
[4, 5],
[7, 8],
[6, 2]])
select = array([0,1,0,0])
result = np.choose(select, m.T)
所以不需要 python 循環或任何東西,numpy 為您提供所有速度優勢。 只需要mT
是因為選擇實際上更像是兩個數組np.choose(select, (m[:,0], m[:1]))
,但是像這樣直接使用它。
使用花哨的索引:
result = m[np.arange(len(select)), select]
如果速度非常重要np.take
,它適用於一維視圖(由於某種原因它相當快,但可能不適用於這些小數組):
result = m.take(select+np.arange(0, len(select) * m.shape[1], m.shape[1]))
我更喜歡使用NP.where進行此類索引任務(而不是NP.ix_ )
OP 中沒有提到的是結果是按位置(源數組中的行/列)還是按某些條件(例如,m >= 5)選擇的。 無論如何,下面的代碼片段涵蓋了這兩種情況。
三個步驟:
創建條件數組;
通過調用NP.where生成索引數組,傳入這個條件數組; 和
將此索引數組應用於源數組
>>> import numpy as NP
>>> cnd = (m==1) | (m==5) | (m==7) | (m==6)
>>> cnd
matrix([[ True, False],
[False, True],
[ True, False],
[ True, False]], dtype=bool)
>>> # generate the index array/matrix
>>> # by calling NP.where, passing in the condition (cnd)
>>> ndx = NP.where(cnd)
>>> ndx
(matrix([[0, 1, 2, 3]]), matrix([[0, 1, 0, 0]]))
>>> # now apply it against the source array
>>> m[ndx]
matrix([[1, 5, 7, 6]])
傳遞給 NP.where 的參數cnd是一個布爾數組,在這種情況下,它是由復合條件表達式(上面的第一行)組成的單個表達式的結果
如果構建這樣的值過濾器不適用於您的特定用例,那很好,您只需要以其他方式生成實際的布爾矩陣( cnd的值)(或直接創建它)。
恕我直言,這是最簡單的變體:
m[np.arange(4), select]
由於標題是指用另一個2D數組索引一個2D數組,因此可以在此處找到實際的通用 numpy 解決方案。
簡而言之:具有任意大維度 m的形狀 (n,m) 索引的二維數組,名為inds
,用於訪問另一個名為B
的形狀 (n,k) 二維數組的元素:
# array of index offsets to be added to each row of inds
offset = np.arange(0, inds.size, inds.shape[1])
# numpy.take(B, C) "flattens" arrays B and C and selects elements from B based on indices in C
Result = np.take(B, offset[:,np.newaxis]+inds)
另一個不使用np.take
並且我覺得更直觀的解決方案如下:
B[np.expand_dims(np.arange(B.shape[0]), -1), inds]
這種語法的優點是它既可以用於基於inds
(如np.take
)從B
讀取元素,也可以用於賦值。
使用python怎么樣?
result = array([subarray[index] for subarray, index in zip(m, select)])
result = array([m[j][0] if i==0 else m[j][1] for i,j in zip(select, range(0, len(m)))])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.