Numpy:查找每行元素的列索引

时间:2016-12-14 14:58:27

标签: python numpy

假设我有一个包含要查找的元素的向量:

a = np.array([1, 5, 9, 7])

现在我有一个矩阵,应该搜索这些元素:

M = np.array([
[0, 1, 9],
[5, 3, 8],
[3, 9, 0],
[0, 1, 7]
])

现在我想得到一个索引数组,告诉M的{​​em> j 的行 j 的哪一列发生a

结果将是:

[1, 0, 1, 2]

Numpy会提供这样的功能吗?

(感谢列表推导的答案,但这不是表现方面的选择。我也为在最后一个问题中提到Numpy而道歉。)

5 个答案:

答案 0 :(得分:3)

请注意以下结果:

M == a[:, None]
>>> array([[False,  True, False],
           [ True, False, False],
           [False,  True, False],
           [False, False,  True]], dtype=bool)

可以使用以下方法检索索引:

yind, xind = numpy.where(M == a[:, None])
>>> (array([0, 1, 2, 3], dtype=int64), array([1, 0, 1, 2], dtype=int64))

答案 1 :(得分:3)

对于每行中的第一个匹配项,在将argmax扩展为2D之后使用a可能是一种有效的方法,如@Benjamin's post中所述 -

(M == a[:,None]).argmax(1)

示例运行 -

In [16]: M
Out[16]: 
array([[0, 1, 9],
       [5, 3, 8],
       [3, 9, 0],
       [0, 1, 7]])

In [17]: a
Out[17]: array([1, 5, 9, 7])

In [18]: a[:,None]
Out[18]: 
array([[1],
       [5],
       [9],
       [7]])

In [19]: (M == a[:,None]).argmax(1)
Out[19]: array([1, 0, 1, 2])

答案 2 :(得分:0)

没有任何导入的懒惰解决方案:

a = [1, 5, 9, 7]

M = [
[0, 1, 9],
[5, 3, 8],
[3, 9, 0],
[0, 1, 7],
]

for n, i in enumerate(M):
    for j in a:
        if j in i:
            print("{} found at row {} column: {}".format(j, n, i.index(j)))

返回:

1 found at row 0 column: 1
9 found at row 0 column: 2
5 found at row 1 column: 0
9 found at row 2 column: 1
1 found at row 3 column: 1
7 found at row 3 column: 2

答案 3 :(得分:0)

也许是这样的?

>>> [list(M[i,:]).index(a[i]) for i in range(len(a))]
[1, 0, 1, 2]

答案 4 :(得分:0)

[sub.index(val) if val in sub else -1 for sub, val in zip(M, a)]
# [1, 0, 1, 2]