[Numpy-discussion] getting indices for array positions

Christian Meesters meesters@uni-mainz...
Wed Feb 7 07:00:52 CST 2007


Hi

This questions might seem stupid, but I didn't get a clever solution myself, 
or found one in the archives, the cookbook, etc. . If I overlooked something, 
please give a pointer.

Well, if I have an 1D array like
[ 0. ,  0.1,  0.2,  0.3,  0.4,  0.5]
,a scalar like 0.122 and want to retrieve the index postion of the closest 
value of the scalar in the array: Is there any fast method to get this?
Right now I've implemented the following method:

def _get_value_index(value, a):
    mindiff = 1e20
    index = 0
    
    for intensity, temp_index in zip(a, xrange(a.shape[0])):
        diff = abs(intensity - value)
        #closer to given value?
        if diff <= mindiff:
            mindiff = diff
            index = temp_index
    return index

It works, but is akward and takes too much time (I've no benchmark), if the 
array is long and the method called often within a different function. But it 
should help clarify the problem.

TIA
Christian


More information about the Numpy-discussion mailing list