![](/img/trans.png)
[英]Find indices of numpy array based on values in another numpy array
[英]Extract values from a numpy array based on another array of 0/1 indices
給定一個僅包含0和1個元素的索引數組idx
,而1s表示感興趣的樣本索引,以及一個樣本數組A
( A.shape[0] = idx.shape[0]
)。 此處的目的是基於索引向量提取樣本的子集。
在matlab中,這樣做很簡單:
B = A(idx,:) %assuming A is 2D matrix and idx is a logical vector
如何以簡單的方式在Python中實現呢?
如果掩碼數組idx
與數組A
形狀相同,那么如果您使用astype
將idx
轉換為布爾數組,則應該能夠提取掩碼指定的元素。
演示-
>>> A
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]])
>>> idx
array([[1, 0, 0, 1, 1],
[0, 0, 0, 1, 0],
[1, 0, 0, 1, 1],
[1, 0, 0, 1, 1],
[0, 1, 1, 1, 1]])
>>> A[idx.astype(bool)]
array([ 0, 3, 4, 8, 10, 13, 14, 15, 18, 19, 21, 22, 23, 24])
使用布爾運算等效於Matlab中的邏輯運算:
B = A[idx.astype(bool)]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.