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]
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]
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
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!