[英]Find index of a vector inside a matrix in Python
Given a matrix ( numpy
array) A
and a vector v
.给定一个矩阵(
numpy
数组) A
和一个向量v
。
A = np.array([[5,0],[1,-2],[0,2],[-1,3],[1,2]])
v = np.array([0,2])
What is the best way to get the index of the vector v in the matrix A (in this case one should get 2).获得矩阵 A 中向量 v 的索引的最佳方法是什么(在这种情况下应该得到 2)。
这样做:
np.argwhere((v == A).all(1))
Out[82]: array([[2]], dtype=int64)
If by best you mean fastest , after thorough experimentation user hpaulj pointed out that np.flatnonzero
is a much faster alternative to np.argwhere
.如果最好的意思是最快的,经过彻底的实验,用户 hpaulj指出
np.flatnonzero
是np.flatnonzero
的更快替代np.argwhere
。 You can use it this way:你可以这样使用它:
np.flatnonzero((v==A).all(1))[0]
Output:输出:
2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.