Python: intersection indices numpy array

前端 未结 4 440
走了就别回头了
走了就别回头了 2020-12-24 05:53

How can I get the indices of intersection points between two numpy arrays? I can get intersecting values with intersect1d:

import numpy as np

a         


        
4条回答
  •  悲&欢浪女
    2020-12-24 06:11

    For Python >= 3.5, there's another solution to do so

    Other Solution

    Let we go through this step by step.

    Based on the original code from the question

    import numpy as np
    
    a = np.array(range(11))
    b = np.array([2, 7, 10])
    inter = np.intersect1d(a, b)
    

    First, we create a numpy array with zeros

    c = np.zeros(len(a))
    print (c)
    

    output

    >>> [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
    

    Second, change array value of c using intersect index. Hence, we have

    c[inter] = 1
    print (c)
    

    output

    >>>[ 0.  0.  1.  0.  0.  0.  0.  1.  0.  0.  1.]
    

    The last step, use the characteristic of np.nonzero(), it will return exactly the index of the non-zero term you want.

    inter_with_idx = np.nonzero(c)
    print (inter_with_idx)
    

    Final output

    array([ 2, 7, 10])
    

    Reference

    [1] numpy.nonzero

提交回复
热议问题