search
Search
Unlock 100+ guides
search toc
close
Outline
Cancel
Post
account_circle
Profile
exit_to_app
Sign out
What does this mean?
Why is this true?
Give me some examples!
search
keyboard_voice
close
Searching Tips
Search for a recipe:
"Creating a table in MySQL"
Search for an API documentation: "@append"
Search for code: "!dataframe"
Apply a tag filter: "#python"
Useful Shortcuts
/ to open search panel
Esc to close search panel
to navigate between search results
d to clear all current filters
Enter to expand content preview
Doc Search
Code Search Beta
SORRY NOTHING FOUND!
mic
Start speaking...
Voice search is only supported in Safari and Chrome.
Shrink
Navigate to

# Finding the closest value in a NumPy array

schedule Aug 10, 2023
Last updated
local_offer
PythonNumPy
Tags
expand_more
mode_heat
Master the mathematics behind data science with 100+ top-tier guides
Start your free 7-days trial now!

To find the closest value in the Numpy array to a certain value, we use the following function:

``` def find_closest(arr, val): idx = np.abs(arr - val).argmin() return arr[idx] ```

We use this like follows:

``` arr = np.array([1,4,10])find_closest(arr, 6) 4 ```

# Explanation

The basic idea is that, the smaller the difference between the number in the array and your value, the closer they are:

``` np.array([1,4,10]) - 6 array([-5, -2, 4]) ```

Since we do not care whether the number in the array is larger or smaller than our value, we take the absolute value:

``` np.abs(np.array([1,4,10]) - 6) array([5, 2, 4]) ```

Next, we want to extract the index of the smallest number in this array since it represents the number that is closest to our value:

``` idx = np.abs(arr - val).argmin()idx 1 ```

Finally, we obtain the actual value that corresponds to this index:

``` return arr[idx] ```
Edited by 0 others
thumb_up
thumb_down
Comment
Citation
Ask a question or leave a feedback...
thumb_up
2
thumb_down
0
chat_bubble_outline
0
settings
Enjoy our search
Hit / to insta-search docs and recipes!