Looking for the fastest way to find the exact overlap between two arrays of equal length in numpy

前端 未结 3 981
一生所求
一生所求 2021-01-14 02:58

I am looking for the optimal (fastest) way to find the exact overlap between two arrays in numpy. Given two arrays x and y

x = array([1,0,3,0,5,0,7,4],dtype=         


        
3条回答
  •  花落未央
    2021-01-14 03:18

    Using numpy.where is the most general solution. but in this particular case, and because it is a useful programming practice, you could use x==y as a mask:

    mask = x==y  
    # mask is  array([ True, False, False,  True,  True,  True, False,  True], dtype=bool)
    
    xf = mask * x
    # xf is array([1, 0, 0, 0, 5, 0, 0, 4])
    

    or directly

    xf = (x==y) * x
    

    imagine now some data X (e.g. 1D for sound, 2D for an image, 3D for a movie, etc...)

    (X<1) * -1. + (X>1) * 1.
    

    returns data with values -1 for an amplitude inferior to 1 and 1. otherwise.

提交回复
热议问题