簡體   English   中英

如何獲取二維 numpy 數組中每一行的前 2 個值的索引,但不包括特定區域?

[英]How to get indices of top 2 values of each row in a 2-D numpy array, but with a specific area is excluded?

例如,我有一個二維數組:

p = np.array([[21,2,3,1,12,13],
             [4,5,6,14,15,16],
             [7,8,9,17,18,19]])
b = np.argpartition(p, np.argmin(p, axis=1))[:, -2:]  
com = np.ones([3,6],dtype=np.int)
com[np.arange(com.shape[0])[:,None],b] = 0
print(com)

b 是 p 中每一行的前 2 個值的索引:

b = [[0 5]
    [4 5]
    [4 5]]

com 是 np.ones 矩陣,大小與 p 相同,索引與 b 相同的元素將變為 0。所以結果是:

com = [[0 1 1 1 1 0]
      [1 1 1 1 0 0]
      [1 1 1 1 0 0]]

現在我還有一個約束:

p[0:2,0:2]

不應考慮這些區域中的數字,因此結果應為:

b = [[4 5]
    [4 5]
    [4 5]]

我怎樣才能做到這一點? 提前致謝!

確保你的問題很清楚。 不確定我是否理解您的限制。 這是一個例子:

# the data
p = np.array([[21, 2, 3, 1, 12, 13],
             [4, 5, 6, 14, 15, 16],
             [7, 8, 9, 17, 18, 19]])

# not sure if this is what you mean by constraint
# but lets ignore values in first two cols and rows
p[0:2, 0:2] = 0

# return the idx of highest values
b = np.argpartition(p, -2)[:, -2:]

暫無
暫無

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

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