Define arguments where two numpy arrays intersect in Python

I have two arrays, let's say:

a, b = np.array([13., 14., 15., 32., 33.]), np.array([15., 16., 17., 33., 34., 47.]) 

I need to find the indices of all elements from a that are not in b. In the above example, the result would be:

 [0, 1, 3] 

Since a [0], a [1] and [3] are equal to 13., 14. and 32., which are absent in b. Please note that I do not need the actual values ​​13., 14. and 32. (I could use set (a) .difference (set (b)) in this case). I am sincerely interested only in indexes.

If possible, the answer should be β€œvectorized”, i.e. do not use a for loop.

+6
source share
3 answers

You can use np.in1d:

 >>> np.arange(a.shape[0])[~np.in1d(a,b)].tolist() [0, 1, 3] 
+3
source

It's pretty simple, use numpy.intersect1d to calculate the elements shared between a and b , then check which of these elements are not in a using numpy.in1d and finally get their position in the array using numpy.argwhere .

 >>> import numpy as np >>> a, b = np.array([13., 14., 15., 32., 33.]), np.array([15., 16., 17., 33., 34., 47.]) >>> np.argwhere(np.in1d(a, np.intersect1d(a,b)) == False) array([[0], [1], [3]]) 

If you prefer a list, just add .flatten to convert the matrix to a vector, and then apply .tolist to get the list:

 >>> np.argwhere(np.in1d(a, np.intersect1d(a,b)) == False).flatten().tolist() [0, 1, 3] 
+2
source

Enough straightforward if you use loops:

 def difference_indices(a, b): # Set to put the unique indices in indices = [] # So we know the index of the element of a that we're looking at a_index = 0 for elem_a in a: found_in_b = False b_index = 0 # Loop until we find a match. If we reach the end of b without a match, the current # a index should go in the indices list while not found_in_b and b_index < len(b): if elem_a == b[b_index]: found_in_b = True b_index = b_index + 1 if not found_in_b: indices.append(a_index) a_index = a_index + 1 return indices 

This should work with lists containing one single type if they are of the same type, and the __eq__ function is defined for this type.

Doing this without loops will require more python knowledge than mine! Hope this is helpful for you.

+1
source

Source: https://habr.com/ru/post/952651/


All Articles