Skip to content

Instantly share code, notes, and snippets.

@RashidLadj
Last active October 16, 2020 15:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RashidLadj/971c7235ce796836853fcf55b4876f3c to your computer and use it in GitHub Desktop.
Save RashidLadj/971c7235ce796836853fcf55b4876f3c to your computer and use it in GitHub Desktop.
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment