NumPy Tip: The index of the array element nearest to some value

Courtesy of Stack Overflow, here’s a little one liner that I use surprisingly frequently. Suppose that you’ve been using an ordered array of numbers arr to do some interpolation and, now that you have the interpolated value v, you want to return only the slice of the array that has arr[i] < v. To do this, you need to find the array index of the element that has the value closest to v, like so:

idx = (np.abs(arr - v)).argmin()

Simple. This finds the deviation between each array element and the value, takes its absolute value, and then returns the index of the element with the smallest value in the resulting array. This, of course, is the number that is closest to v. You can then slice arr using idx, as you would with any other list or array.

About Phil Bull

I'm a theoretical cosmologist, currently working as a NASA NPP fellow at JPL/Caltech in Pasadena, CA. My research focuses on the effects of inhomogeneities on the evolution of the Universe and how we measure it. I'm also keen on stochastic processes, scientific computing, the philosophy of science, and open source stuff. View all posts by Phil Bull

3 responses to “NumPy Tip: The index of the array element nearest to some value

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: