Suppose we have an array A
and a set of arrays in B
. What's the fast way to find how many items in A
exist in each row of B
? For example, if I have:
A = np.array([2, 5, 10])
B = np.array([(3, 5, 10), (1, 2, 5), (4, 6, 9)])
So I should get C = [2, 2, 0]
.
CodePudding user response:
You can also use broadcasting:
(B==A[:,None,None]).sum((0,2))
Output:
array([2, 2, 0])
CodePudding user response:
np.count_nonzero(np.isin(B, A), axis=1)
might be a way of achieving the result you look for. Or, in a more elegant way - as of by suggestion of @mozway - np.isin(B, A).sum(axis=1)
.