2016-12-14 75 views
3

假设我有一个元素的向量发现:NumPy的:查找元素列索引每行

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

现在我已经在那里这些因素应搜索的矩阵:

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

现在我想要得到一个索引数组,告诉列jM元素ja发生。

其结果将是:

[1, 0, 1, 2] 

不numpy的提供这样的功能呢?

(感谢您与列表内涵的答案,但是这不是一个选项,性能方面我也只是在最后一个问题提NumPy的道歉。)

回答

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)) 
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 
0

也许这样的事情?

>>> [list(M[i,:]).index(a[i]) for i in range(len(a))] 
[1, 0, 1, 2] 
0
[sub.index(val) if val in sub else -1 for sub, val in zip(M, a)] 
# [1, 0, 1, 2] 
3

对于每一行的第一个比赛,它可能是一个有效的方法在将a延伸至2D之后使用argmax,如@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])