Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy: find index of elements in one array that occur in another array

I have two 1D arrays and I want to find out if an element in one array occurs in another array or not.

For example:

import numpy as np
A = np.array([ 1, 48, 50, 78, 85, 97])
B = np.array([38, 43, 50, 62, 78, 85])

I want:

C = [2,3,4] # since 50 in second array occurs in first array at index 2, 
            # similarly 78 in second array occurs in first array in index 3,
            # similarly for 85, it is index 4

I tried:

accuracy = np.searchsorted(A, B)

But it gives me undesirable results.

like image 887
Lanc Avatar asked Mar 06 '15 14:03

Lanc


People also ask

How do you check if elements of an array are in another array Python?

Use numpy. isin() to find the elements of a array belongs to another array or not. it returns a boolean array matching the shape of other array where elements are to be searched.

How do you check if all elements of an array are in another array?

Use the inbuilt ES6 function some() to iterate through each and every element of first array and to test the array. Use the inbuilt function includes() with second array to check if element exist in the first array or not. If element exist then return true else return false.

How do I check if a NumPy array is in another array?

By using Python NumPy np. array_equal() function or == (equal operator) you check if two arrays have the same shape and elements. These return True if it has the same shape and elements, False otherwise.

How do you find the common values between two arrays in NumPy?

In NumPy, we can find common values between two arrays with the help intersect1d(). It will take parameter two arrays and it will return an array in which all the common elements will appear.


2 Answers

You could use np.where and np.in1d:

>>> np.where(np.in1d(A, B))[0]
array([2, 3, 4])

np.in1d(A, B) returns a boolean array indicating whether each value of A is found in B. np.where returns the indices of the True values. (This will also work if your arrays are not sorted.)

like image 84
Alex Riley Avatar answered Nov 15 '22 22:11

Alex Riley


You should start with np.intersect1d, which finds the set intersection (common elements) between arrays.

In [5]: np.intersect1d(A, B)
Out[5]: array([50, 78, 85])

To get the desired output from your question, you can then use np.searchsorted with just those items:

In [7]: np.searchsorted(A, np.intersect1d(A, B))
Out[7]: array([2, 3, 4])
like image 24
perimosocordiae Avatar answered Nov 15 '22 21:11

perimosocordiae