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!
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.
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.
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.
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With