kevinkayaks
kevinkayaks

Reputation: 2726

find indices where one array is larger than an element in a second array

I have two arrays

a = np.array([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])
b = np.array([0,5,10,15])

I want an output array with the length of b where each element b[i] is the index of the first element of a which is at least b[i]:

out = np.array([0, 5, 10, 15]

A slow solution is:

out = []
for x in b: 
    i = np.argmax( a >= x )
    out.append( i )

and this is a marginal speed increase:

out = []
i=0
for x in b: 
    i = np.argmax( a[i:] >= x ) + i
    out.append( i )

Any ideas for a pure numpy solution? This is prohibitively slow. Thanks

Upvotes: 3

Views: 332

Answers (1)

Bi Rico
Bi Rico

Reputation: 25813

If a is sorted, you can use a.searchsorted(b).

Upvotes: 3

Related Questions