Search code examples
python-2.7numpyintervalsmatrix-indexing

Indices such that elements are in the closed interval


I got a numpy 1d arrays, and I want to find the indices of the array such that its values are in the closed interval specified by another 1d array. To be concrete, here is an example

A= np.array([  0.69452994,   3.4132039 ,   6.46148658,  17.85754453,
        21.33296454,   1.62110662,   8.02040621,  14.05814177,
        23.32640469,  21.12391059])
b = np.array([  0. ,   3.5,   9.8,   19.8 ,  50.0])

I want to find the indices in b such that values in A are in which closed interval (b is always in sorted order starting from 0 and ending in the max possible value A can ever take.

In this specific example, my output will be

indx = [0,0,1,2,3,0,1,2,3,3]

How can I do it ?. I tried with np.where, without any success.


Solution

  • Given the sorted nature of b, we can simply use searchsorted/digitize to get the indices where elements off A could be placed to keep the sorted order, which in essence means getting the boundary indices for each of the b elements and finally subtract 1 from those indices for the desired output.

    Thus, assuming the right-side boundary is an open one, the solution would be -

    np.searchsorted(b,A)-1
    np.digitize(A,b,right=True)-1
    

    For left-side open boundary, use :

    np.searchsorted(b,A,'right')-1
    np.digitize(A,b,right=False)-1