Find elements of array one nearest to elements of array two

后端 未结 1 561
离开以前
离开以前 2020-11-27 22:07

This answer explains how to find the nearest (sorted) array element to a single point, in a manner efficient for large arrays (slightly modified):

d         


        
1条回答
  •  难免孤独
    2020-11-27 22:50

    You can make few changes to extend it for an array of elements in value, like so -

    idx = np.searchsorted(xx, yy, side="left").clip(max=xx.size-1)
    mask = (idx > 0) &  \
           ( (idx == len(xx)) | (np.fabs(yy - xx[idx-1]) < np.fabs(yy - xx[idx])) )
    out = xx[idx-mask]
    

    Explanation

    Nomenclature : array is the array in which we are looking to place elements from value to maintain the sorted nature of array.

    Changes needed to extend the solution for a single element to many elements for searching :

    1] Clip the indices array idx obtained from np.searchsorted at a max. of array.size-1, because for elements in value that are larger than the maximum of array, we need to make idx indexable by array.

    2] Introduce numpy to replace math to do those operations in a vectorized manner.

    3] Replace the conditional statement by the trick of idx - mask. In this case, internally Python would up-convert mask to an int array to match up with the datatype of idx. Thus, all the True elements become 1 and thus for True elements we would effectively have idx-1, which is the True case of the IF conditional statement in the original code.

    0 讨论(0)
提交回复
热议问题