簡體   English   中英

2d數組的每列的第一個和最后一個數字1的索引

[英]Index of the first and last numbers 1 of each column of an 2d array

我有一個2d數組( Q )只包含0和1(二進制矩陣)。 對於Q每一列,我想找到值1出現的第一行和最后一行的索引。 每列至少包含一個1

這是一個例子:

[[1, 1, 1, 0, 0, 0, 0],
 [0, 1, 1, 1, 0, 0, 0],
 [1, 0, 0, 0, 1, 0, 1],
 [0, 0, 0, 1, 0, 1, 1],
 [1, 0, 1, 0, 0, 0, 0],
 [0, 0, 1, 0, 0, 0, 1],
 [0, 0, 0, 1, 0, 1, 0]]

boundsList = {0: (0, 4), 1: (0, 1), 2: (0, 5), 3: (1, 6), 4: (2, 2), 5: (3, 6), 6: (2, 5)}

我實現了一個算法,它可以工作,但對於大型數組,它效率不高:

boundsList = {}
for i in range (0, len(Q)):
    column = Q[:,i]
    indexesList = []
    for idx, pos in enumerate (column):
        if pos == 1:
            indexesList.append(idx)
    boundsList[i] = (indexesList[0], indexesList[-1])

任何人都可以建議另一個簡單的解決方案嗎?

讓我們從你的數組開始:

>>> Q
array([[1, 1, 1, 0, 0, 0, 0],
       [0, 1, 1, 1, 0, 0, 0],
       [1, 0, 0, 0, 1, 0, 1],
       [0, 0, 0, 1, 0, 1, 1],
       [1, 0, 1, 0, 0, 0, 0],
       [0, 0, 1, 0, 0, 0, 1],
       [0, 0, 0, 1, 0, 1, 0]])

要獲取包含1的第一行的每列的索引:

>>> np.argmax(Q, axis=0) # Index of first appearance of 1
array([0, 0, 0, 1, 2, 3, 2])

要獲取包含1的最后一行的每列的索引:

>>> Q.shape[0] - np.argmax(Q[::-1, :], axis=0) - 1 # Index of last appearance of 1
array([4, 1, 5, 6, 2, 6, 5])

要將它們組合成您喜歡的字典:

>>> dict(enumerate(zip( np.argmax(Q, axis=0), Q.shape[0] - np.argmax(Q[::-1, :], axis=0) - 1)))
{0: (0, 4), 1: (0, 1), 2: (0, 5), 3: (1, 6), 4: (2, 2), 5: (3, 6), 6: (2, 5)}

可能最快的方法是使用argmax方法(它可以工作,因為它從兩側找到第一個最大值的位置),然后將其放入字典中。 與使用np.argmax相比, argmax方法具有更少的開銷(常數因子),因此,特別是對於小型數組,該方法將更快。

因為dictenumeratezip在列表上比數組更快我也將中間數組轉換為列表( tolist方法是實現它的最快方法):

>>> dict(enumerate(zip(Q.argmax(axis=0).tolist(), 
...                    (Q.shape[0]-1-Q[::-1].argmax(axis=0)).tolist())))
{0: (0, 4), 1: (0, 1), 2: (0, 5), 3: (1, 6), 4: (2, 2), 5: (3, 6), 6: (2, 5)}

Q[::-1]是反向數組,為了得到“未反轉”的索引,我必須從Q.shape[0]-1減去它們。

暫無
暫無

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

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