欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

在numpy数组中查找最接近的值

程序员文章站 2022-05-18 17:16:14
...

本文翻译自:Find nearest value in numpy array

Is there a numpy-thonic way, eg function, to find the nearest value in an array? 是否有numpy-thonic方法(例如函数)在数组中查找最接近的值

Example: 例:

np.find_nearest( array, value )

#1楼

参考:https://stackoom.com/question/Aldk/在numpy数组中查找最接近的值


#2楼

With slight modification, the answer above works with arrays of arbitrary dimension (1d, 2d, 3d, ...): 稍作修改,上面的答案就可以处理任意维数(1d,2d,3d等)的数组:

def find_nearest(a, a0):
    "Element in nd array `a` closest to the scalar value `a0`"
    idx = np.abs(a - a0).argmin()
    return a.flat[idx]

Or, written as a single line: 或者,写成一行:

a.flat[np.abs(a - a0).argmin()]

#3楼

Here's a version that will handle a non-scalar "values" array: 这是将处理非标量“值”数组的版本:

import numpy as np

def find_nearest(array, values):
    indices = np.abs(np.subtract.outer(array, values)).argmin(0)
    return array[indices]

Or a version that returns a numeric type (eg int, float) if the input is scalar: 如果输入是标量,则返回一个数字类型(例如,int,float)的版本:

def find_nearest(array, values):
    values = np.atleast_1d(values)
    indices = np.abs(np.subtract.outer(array, values)).argmin(0)
    out = array[indices]
    return out if len(out) > 1 else out[0]

#4楼

Here's an extension to find the nearest vector in an array of vectors. 这是在向量数组中查找最近的向量的扩展。

import numpy as np

def find_nearest_vector(array, value):
  idx = np.array([np.linalg.norm(x+y) for (x,y) in array-value]).argmin()
  return array[idx]

A = np.random.random((10,2))*100
""" A = array([[ 34.19762933,  43.14534123],
   [ 48.79558706,  47.79243283],
   [ 38.42774411,  84.87155478],
   [ 63.64371943,  50.7722317 ],
   [ 73.56362857,  27.87895698],
   [ 96.67790593,  77.76150486],
   [ 68.86202147,  21.38735169],
   [  5.21796467,  59.17051276],
   [ 82.92389467,  99.90387851],
   [  6.76626539,  30.50661753]])"""
pt = [6, 30]  
print find_nearest_vector(A,pt)
# array([  6.76626539,  30.50661753])

#5楼

If you don't want to use numpy this will do it: 如果您不想使用numpy,可以这样做:

def find_nearest(array, value):
    n = [abs(i-value) for i in array]
    idx = n.index(min(n))
    return array[idx]

#6楼

import numpy as np
def find_nearest(array, value):
    array = np.asarray(array)
    idx = (np.abs(array - value)).argmin()
    return array[idx]

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]

value = 0.5

print(find_nearest(array, value))
# 0.568743859261