[Numpy-discussion] getting indices for array positions

Robert Cimrman cimrman3@ntc.zcu...
Wed Feb 7 07:32:08 CST 2007


Christian Meesters wrote:
>> Try searchsorted.
> Thanks, but that doesn't work. Sorry, if my question wasn't clear.
> 
> To illustrate the requirement:
> For instance:
>>>> a
> array([ 0. ,  0.1,  0.2,  0.3,  0.4])
>>>> # should be 1
> ...
>>>> a.searchsorted(0.11)
> 2
>>>> # should be 2
> ...
>>>> a.searchsorted(0.16)
> 2
> 
> I could correct for one index position, of course, but I still have the 
> requirement to get the index of the item with the closest value to the key. 
> Since searchsorted returns the index of the first item in a that is >= or > 
> the key, it can't make the distinction between 0.1 and 0.2 as I would like to 
> have.

I see. But it gives you the index (say 'ii') of the first item that is
grater than your scalar - then you just have to compare your scalar with
a[ii] and a[ii-1] and choose whichever is closer, no?

r.


More information about the Numpy-discussion mailing list