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.

### Like this:

Like Loading...

*Related*

## 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
August 20th, 2015 at 4:10 pm

Thanks! Really efficient method.

November 26th, 2015 at 10:05 am

[…] values. How to efficiently find tthe closest interpolated values of rach elements of A in I ? That post give me 90% of the answer. It details how to efficiently find the index of a single value v […]

August 6th, 2016 at 4:35 pm

perfect. very helpful. Thanks