Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the set of indices where two vectors have equal elements in Python

I have two vectors in Python: Predictions and Labels. What I would like to do is to find out the set of indices where these two vectors have equal elements. For example, lets say the vectors are:

Predictions = [4, 2, 5, 8, 3, 4, 2, 2]

     Labels = [4, 3, 4, 8, 2, 2, 1, 2]

So the set of indices where the two vectors have equal elements would be:

Indices = [0, 3, 7]

How can I get this in Python? Without using for-loops etc. Is there a built-in function for example in numpy?

Thank you for any help!

like image 498
jjepsuomi Avatar asked Jun 04 '15 08:06

jjepsuomi


People also ask

How do you get the multiple index of an element in a list in Python?

One of the most basic ways to get the index positions of all occurrences of an element in a Python list is by using a for loop and the Python enumerate function. The enumerate function is used to iterate over an object and returns both the index and element.

How do you find the equality of two arrays in Python?

Method 1: We generally use the == operator to compare two NumPy arrays to generate a new array object. Call ndarray. all() with the new array object as ndarray to return True if the two NumPy arrays are equivalent.

How do you find the index of a element in a matrix in Python?

Get the index of elements in the Python loop Create a NumPy array and iterate over the array to compare the element in the array with the given array. If the element matches print the index.

How do you extract all numbers between a given range from a NumPy array?

Using the logical_and() method The logical_and() method from the numpy package accepts multiple conditions or expressions as a parameter. Each of the conditions or the expressions should return a boolean value. These boolean values are used to extract the required elements from the array.


1 Answers

This is one way of doing it with numpy:

np.where(np.equal(Predictions, Labels))

which is equivalent to:

np.equal(Predictions, Labels).nonzero()

It will return a single element tuple though, so to get the actual array, add [0] as in:

np.equal(Predictions, Labels).nonzero()[0]
like image 76
Andrzej Pronobis Avatar answered Oct 15 '22 01:10

Andrzej Pronobis