- Help Center
- Python Programming
-
Data Science Bootcamp
-
Python Programming
-
Machine Learning
-
Data Analysis
-
Pricing
-
Registration
-
R Language
-
SQL
-
Power BI
-
Homework and Notebooks
-
Platform Related Issues
-
Programming and Tools
-
Large Language Models Bootcamp
-
Blog
-
Employment Assistance
-
Partnerships
-
Data Science for Business
-
Python for Data Science
-
Introduction to Power BI
How will you find the nearest value in a given numpy array?
We can use the argmin() method of numpy as shown below:
import numpy as np
def find_nearest_value(arr, value):
arr = np.asarray(arr)
idx = (np.abs(arr - value)).argmin()
return arr[idx]
#Driver code
arr = np.array([ 0.21169, 0.61391, 0.6341, 0.0131, 0.16541, 0.5645, 0.5742])
value = 0.52
print(find_nearest_value(arr, value)) # Prints 0.5645