繁体   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