[英]Numpy: Find column index for element on each row
假設我有一個包含要查找的元素的向量:
a = np.array([1, 5, 9, 7])
現在我有一個矩陣,應該搜索這些元素:
M = np.array([
[0, 1, 9],
[5, 3, 8],
[3, 9, 0],
[0, 1, 7]
])
現在,我想獲得一個索引數組中的j行的哪一列告訴M
的單元j a
出現。
結果將是:
[1, 0, 1, 2]
Numpy會提供這樣的功能嗎?
(感謝列表推導的答案,但這不是表現方面的選擇。我也為在最后一個問題中提到Numpy而道歉。)
注意結果:
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))
對於每一行的第一場比賽,這可能是使用的有效方式argmax
擴展后a
在做2D @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])
沒有任何導入的懶惰解決方案:
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
也許是這樣的?
>>> [list(M[i,:]).index(a[i]) for i in range(len(a))]
[1, 0, 1, 2]
[sub.index(val) if val in sub else -1 for sub, val in zip(M, a)]
# [1, 0, 1, 2]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.