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

I have two vectors in Python: Predictionsand Labels. What I would like to do is figure out a set of indices in which these two vectors have equal elements. For example, suppose that the vectors:

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

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

Thus, a set of indices in which two vectors have the same elements will 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?

Thanks for the help!

+4
source share
2 answers

This is one way to do this with numpy:

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

which is equivalent to:

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

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

np.equal(Predictions, Labels).nonzero()[0]
+6

a, b :

a = np.array([1, 2, 3, 4, 5])
b = np.array([1, 3, 2, 4, 5])

np.equal(a,b) , a==b (, , ):

> array([ True, False, False,  True,  True], dtype=bool)

, .

np.where() :

np.where(a > 2)
> (array([2, 3, 4]),)

, np.where np.equal - , :

np.where(np.equal(a,b))
> (array([0, 3, 4]),)

edit: , , ^^

+3

All Articles