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

How to Find the Nearest Value in a NumPy Array?

Linda Hamilton
Release: 2024-12-07 19:48:13
Original
689 people have browsed it

How to Find the Nearest Value in a NumPy Array?

Identifying the Nearest Value in NumPy Arrays

Determining the element closest to a specified value within a NumPy array can be a common task. The np.find_nearest() function offers a convenient method to locate such a value.

Custom Function Approach

Here's a custom NumPy implementation of the find_nearest() function:

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 takes an array and a target value as arguments. It utilizes NumPy's np.abs() function to compute the absolute difference between each element in the array and the target value. The argmin() function is then employed to identify the index position of the minimum absolute difference.

Example Usage

Consider the following NumPy array:

array = np.random.random(10)
print(array)
# [ 0.21069679  0.61290182  0.63425412  0.84635244  0.91599191  0.00213826
#   0.17104965  0.56874386  0.57319379  0.28719469]
Copy after login

To search for the value closest to 0.5, we can call the find_nearest() function:

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

The function correctly identifies the element in the array with the smallest difference from the target value of 0.5.

The above is the detailed content of How to Find the Nearest 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