Home > Backend Development > Python Tutorial > How to Find the Closest Value in a NumPy Array?

How to Find the Closest Value in a NumPy Array?

Barbara Streisand
Release: 2024-11-29 21:00:13
Original
1011 people have browsed it

How to Find the Closest Value in a NumPy Array?

Finding Nearest Value in a Numpy Array

In numpy, finding the nearest value to a given target value can be achieved through a straightforward process. Let's define a function to accommodate this requirement:

import numpy as np

def find_nearest(array, value):
    array = np.asarray(array)
    idx = (np.abs(array - value)).argmin()
    return array[idx]
Copy after login

This function accepts an array and a target value. It converts the array to a numpy array and calculates the absolute differences between each element of the array and the target value. The index of the element with the smallest absolute difference is determined using argmin(). Finally, the element at that index is returned.

Example Usage:

Let's illustrate the usage of the find_nearest() function with an example:

array = np.random.random(10)
print(array)

print(find_nearest(array, value=0.5))
Copy after login

In this example, a random array of 10 elements is created. The find_nearest() function is then used to find the element in the array that is closest to 0.5. The output will be the nearest value in the array to 0.5.

The above is the detailed content of How to Find the Closest Value in a NumPy Array?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template