pythonarraysnumpysortingcorrespondence

Python - Find correspondence in an array


I have a large 2D array (3x100,000) of 3D coordinates and a second 1D array with certain not sorted coordinates. I would like to find all points with coordinates that contained in the second array

An example:

mat1 = np.array([[1,2,3],[1,2,5],[2,3,6],[10,11,12],[20,2,3]])

mat2 = np.array([1,2,3,6])

So here I need to obtain indexes of 0 and 2. And I need to find each correspondence on around 100,000 coordinates. Is there a specific function in Python to do this work?

To sum up my situation:

enter image description here


Solution

  • Easiest way would be with np.isin -

    # a,b are input arrays - mat1,mat2 respectively
    In [7]: np.flatnonzero(np.isin(a,b).all(1))
    Out[7]: array([0, 2])
    

    Another with np.searchsorted -

    In [19]: idx = np.searchsorted(b,a)
    
    In [20]: idx[idx==len(b)] = 0
    
    In [21]: np.flatnonzero((b[idx]==a).all(1))
    Out[21]: array([0, 2])
    

    If b is not in sorted order, use np.argsort(b) as sorter arg with np.searchsorted. More info.