1

Given a matrix (numpy array) A and a vector 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).

1
  • If the values are unique (distinct), how about A[A == v][2] ? Commented Mar 11, 2020 at 12:43

2 Answers 2

1

This does it:

np.argwhere((v == A).all(1))
Out[82]: array([[2]], dtype=int64)
Sign up to request clarification or add additional context in comments.

Comments

1

If by best you mean fastest, after thorough experimentation user hpaulj pointed out that np.flatnonzero is a much faster alternative to np.argwhere. You can use it this way:

np.flatnonzero((v==A).all(1))[0]

Output:

2

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.