Exemples de comment trouver l'élément d'une matrice le plus proche d'une valeur donnée sous python
Tableau 1D
Cas d'une matrice à une dimension
>>> import numpy as np>>> value = 0.5>>> A = np.random.random(10)>>> Aarray([ 0.47009242, 0.40242778, 0.02064198, 0.47456175, 0.83500227,0.53205104, 0.14001715, 0.86691798, 0.78473226, 0.91123132])>>> idx = (np.abs(A-value)).argmin()>>> idx3>>> A[idx]0.47456175235592957
Tableau 2D
Cas d'une matrice à plusieurs dimensions
>>> A = np.random.random((4,4))>>> Aarray([[ 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])>>>
Autre exemple:
>>> value = [0.2, 0.5]>>> A = np.random.random((4,4))>>> Aarray([[ 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))>>> Barray([[ 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])
Références
| Liens | Site |
|---|---|
| find nearest value in numpy array | stackoverflow |
| Finding the nearest value and return the index of array in Python | stackoverflow |
| Numpy minimum in (row, column) format | stackoverflow |
| Numpy: get the column and row index of the minimum value of a 2D array | stackoverflow |
| numpy : argmin in multidimensional arrays | bytes.com |
| numpy.square | doc scipy |
| Array creation | doc scipy |
