[Numpy-discussion] Find insertion point
Warren Weckesser
warren.weckesser@enthought....
Tue Aug 17 11:42:13 CDT 2010
Nikolaus Rath wrote:
> Hello,
>
> I want to find the first i such that x[i] < y and x[i+1] >= y. Is there
> a way to do this without using a Python loop?
>
> I can't use np.searchsorted(), because my x array crosses y several
> times.
>
>
> Best,
>
> -Nikolaus
>
>
Here's one way:
In [32]: x
Out[32]: array([10, 3, 2, 5, 8, 7, 6, 5, 4, 7, 11])
In [33]: y = 4.1
In [34]: np.where((x[:-1] < y) & (x[1:] > y))[0][0]
Out[34]: 2
In [35]: y = 9.5
In [36]: np.where((x[:-1] < y) & (x[1:] > y))[0][0]
Out[36]: 9
(The second index [0] assumes that at least one such point is found.)
Warren
More information about the NumPy-Discussion
mailing list