Skip to content
{{ message }}

Instantly share code, notes, and snippets.

# RashidLadj/intersect2D.py

Last active Oct 16, 2020
Python function to find the intersection between two 2D (or nD) numpy arrays, i.e. intersection of rows
 import numpy as np def intersect2D(Array_A, Array_B): """ Find row intersection between 2D numpy arrays, a and b. """ # ''' Using Tuple ''' # intersectionList = np.asarray([x for x in Array_A for y in Array_B if(tuple(x) == tuple(y))]) # ''' Using Numpy array_equal ''' # """ This method is valid for an ndarray """ intersectionList = np.asarray([x for x in Array_A for y in Array_B if(np.array_equal(x, y))]) # """ Using set and bitwise and intersectionList = [list(y) for y in (set([tuple(x) for x in a]) & set([tuple(x) for x in b]))] return intersectionList ########################################### import numpy as np def intersect2D(Array_A, Array_B): """ Find row intersection between 2D numpy arrays, a and b. """ # ''' Using Tuple ''' # intersectionList = list(set([tuple(x) for x in Array_A for y in Array_B if(tuple(x) == tuple(y))])) print ("intersectionList (not Empty) = \n",intersectionList) # ''' Using Numpy function "array_equal" ''' # """ This method is valid for an ndarray """ intersectionList = list(set([tuple(x) for x in Array_A for y in Array_B if(np.array_equal(x, y))])) print ("intersectionList (not Empty) = \n",intersectionList) # ''' Using set and bitwise and ''' intersectionList = [list(y) for y in (set([tuple(x) for x in Array_A]) & set([tuple(x) for x in Array_B]))] print ("intersectionList (not Empty) = \n",intersectionList) return intersectionList ## Example with Intersection don't empty ## ########################################### a =([[941., 672.], [945., 658.], [952., 658.], [953., 668.], [954., 670.]]) b =([[941., 672.], [952., 658.], [952., 658.], [952., 659.]]) intersectionList= intersect2D(a, b) ######################################## ## Example with Intersection is empty ## ######################################## a =np.asarray([[941., 672.], [945., 658.], [952., 658.], [953., 668.], [954., 670.]]) b =np.asarray([[941., 675.], [952., 669.], [952., 659.]]) intersectionList = intersect2D(a, b)
to join this conversation on GitHub. Already have an account? Sign in to comment