How to determine the nearest value and its index in an array using numpy ?


Numpy is a library for scientific computing in Python, and it provides several functions to find the nearest value and its index in an array:

Using argmin() function

One of the most commonly used methods is using numpy's argmin() function. This allows us to search through an entire array to find the closest number (or value) and its corresponding index. For example, say we have an array of numbers:

import numpy as np

A = np.random.random(10)

This code generate for example

array([ 0.47009242,  0.40242778,  0.02064198,  0.47456175,  0.83500227,
        0.53205104,  0.14001715,  0.86691798,  0.78473226,  0.91123132])

We can use numpy's argmin() function to find the index of the closest value of

value = 0.5

idx = (np.abs(A-value)).argmin()

in this case it would be

3

Note that:

A[idx]

gives

0.47456175235592957

Other example with multidimensional array

Example 1

In the case of a multidimensional array:

>>> A = np.random.random((4,4))
>>> A
array([[ 0.81497314,  0.63329046,  0.53912919,  0.19661354],
       [ 0.71825277,  0.61201976,  0.0530397 ,  0.39322394],
       [ 0.41617287,  0.00585574,  0.26575708,  0.39457519],
       [ 0.25185766,  0.06262629,  0.69224089,  0.89490705]])
>>> X = np.abs(A-value)
>>> idx = np.where( X == X.min() )
>>> idx
(array([0]), array([2]))
>>> A[idx[0], idx[1]]
array([ 0.53912919])
>>>

Example 2

>>> value = [0.2, 0.5]
>>> A = np.random.random((4,4))
>>> A
array([[ 0.36520505,  0.91383364,  0.36619464,  0.14109792],
       [ 0.19189167,  0.10502695,  0.39406069,  0.04107304],
       [ 0.96210652,  0.5862801 ,  0.12737704,  0.33649882],
       [ 0.91871859,  0.95923748,  0.4919818 ,  0.72398577]])
>>> B = np.random.random((4,4))
>>> B
array([[ 0.61142891,  0.90416306,  0.07284985,  0.86829844],
       [ 0.2605821 ,  0.48856753,  0.55040045,  0.65854238],
       [ 0.83943169,  0.64682588,  0.50336359,  0.90680018],
       [ 0.82432453,  0.10485762,  0.6753372 ,  0.77484694]])
>>> X = np.sqrt( np.square( A - value[0] ) +  np.square( B - value[1] ) )
>>> idx = np.where( X == X.min() )
>>> idx
(array([2]), array([2]))
>>> A[idx[0], idx[1]]
array([ 0.12737704])
>>> B[idx[0], idx[1]]
array([ 0.50336359])

References

Links Site
numpy.square doc scipy
Array creation doc scipy