user6514554
user6514554

Reputation:

How to check arrays with numpy python

I have two arrays and i want to check how many integers are the same in the different arrays. The problem i'm having is that it only shows me how many are the same when they are in the same position. Both arrays have 15 numbers in them. Example:

import numpy as np
a = np.array([1, 4, 5, 7, 9, 14, 15, 17, 18, 19, 21, 22, 23, 25, 26])
b = np.array([8, 28, 12, 3, 24, 16, 23, 19, 14, 2, 11, 29, 27, 6, 13])
print(np.count_nonzero(a==b))

This prints 0 even though there's clearly integers that are the same. How can i make this print how many integers have the same value?

Upvotes: 2

Views: 105

Answers (2)

cs95
cs95

Reputation: 402253

You can perform broadcasted comparison between b and a, and then just tally up the matches:

(b == a[:, None]).sum()
3

This checks out since you have [14, 19, 23] as the common elements.

Upvotes: 2

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 95873

You want to use np.intersect1d, if I am understanding you correctly:

In [12]: import numpy as np

In [13]: a = np.array([1, 4, 5, 7, 9, 14, 15, 17, 18, 19, 21, 22, 23, 25, 26])
    ...: b = np.array([8, 28, 12, 3, 24, 16, 23, 19, 14, 2, 11, 29, 27, 6, 13])
    ...:

In [14]: np.intersect1d(a, b)
Out[14]: array([14, 19, 23])

Upvotes: 3

Related Questions