[Numpy-discussion] getting indices for array positions

Stefan van der Walt stefan@sun.ac...
Wed Feb 7 08:08:27 CST 2007


On Wed, Feb 07, 2007 at 02:00:52PM +0100, Christian Meesters wrote:
> 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?

If I understand correctly:

data = N.array([ 0. ,  0.1,  0.2,  0.3,  0.4,  0.5])
diff = N.abs(data - val)
print N.argmin(diff)

Regards
Stéfan


More information about the Numpy-discussion mailing list