如何在 Numpy 数组中查找最近值?

各位读者大家好!Python 中有许多库可用于执行不同的功能。Numpy 库就是其中之一,用于在 Python 中处理数组。在许多像排序这样的例子中,您需要找出数组中最接近的值。通过这种方式,您可以使用此方法按升序和降序对数组进行排序。这种寻找最接近值的技术只不过是搜索方法。检索方法用于处理数据库。因此,简单来说,我们可以说在 numpy 数组中查找最接近的值只是解决复杂问题的一小部分。在本文中,我们将了解 numpy 数组的详细信息以及如何在 numpy 数组中查找最接近的值。

numpy 数组

numpy 数组包含相同类型的值。数组的索引采用正整数格式。数组中的对象称为ndarray。numpy 库中的 array() 函数用于在 python 中创建数组。现在让我们看看如何在 python 中创建 numpy 数组。

示例 1:如何在 python 中创建 numpy 数组

为了首先在 python 中创建 numpy 数组,我们需要导入numpy库。第二步包括使用 array() 函数/方法。我们可以将列表、数组和元组作为ndarray传递。

import numpy as np
Array = np.array([1,3,5,7,9])
print (Array)

输出:

创建 Numpy 数组

我们还可以使用这个 numpy 库创建多维数组。您可以在此处找到与 numpy 数组相关的更多详细信息

numpy 数组中的最近值

使用这两个函数在 numpy 数组中查找最接近的值非常简单。这些函数是numpy.abs()numpy.argmin()。

numpy.abs() 函数

麻木的。abs()函数也称为numpy.absolute()函数。该函数有助于计算 numpy 数组元素之间的绝对值。简而言之,我们可以说它为每个负值返回正值或删除数字的负号。

示例 2:numpy.abs() 函数的工作原理

现在让我们看看 python 中 numpy.abs() 函数的工作原理。在示例 2 中,我们仅将一个简单数组传递给 numpy.abs() 函数。输出将是 numpy 数组所有元素的绝对值。

import numpy as np
array1 = [2,-4,7,15,23,8,24,-5,-10]
print ("Absolute Value of array1 : \n", np.absolute(array1))

输出:

Numpy.abs() 函数

numpy.argmin() 函数

麻木的。argmin() 函数始终返回 numpy 数组中存在的最小数字的索引号。numpy 最小值函数的工作原理类似,但它返回 numpy 数组中的最小值/数字。麻木。argmin() 函数始终返回最小数字的索引。输出始终采用索引号的形式。

示例 3:numpy.argmin() 函数的工作原理

在示例 3 中,我们将看到 numpy.argmin 函数在 python 中的基本实现。

import numpy as np
Array =np.array([1,2,3,6,9,0])
A = np.argmin(Array)
print(A)

根据示例 3,numpy 数组包含六个值。0 是其中最小/最小值,因此 numpy.argmin() 函数应返回 0 的索引号,即 5。

输出:

Numpy.argmin() 函数

现在让我们结合这两个函数来找出 numpy 数组中最接近的值。

示例 4:如何在 numpy 数组中查找最接近的值?

import numpy as np
 
Array = np.array([12,13,8,10,11,45])
 
x =7 # value to which nearest element is to be found
print("value is: ",x)
  
dif_Array = np.absolute(Array-x) # use of absolute() function to find the difference
  
index = dif_Array.argmin() # find the index of minimum difference element
print("Nearest element to the given values is : ", Array[index])
print("Index of nearest value is : ", index)

在示例 4 中,我们简单地使用numpy.absolute()函数和numpy.argmin()函数的组合来解决问题。首先,我们导入 numpy 库并使用array()函数初始化 numpy 数组。然后设置要查找最近元素的值。在接下来的步骤中,我们使用absolute函数来找出numpy数组的每个元素与我们选择的值x之间的差异。这些差异存储在新数组diff_Array中。接下来,我们使用argmin()函数查找 diff_Array 中最小数字的索引。因此,通过这种方式,我们可以在 numpy 数组中找到最接近的值。

输出:

在 Python 中使用 Numpy 库求最近值

这样,我们也可以找出多维numpy数组中最接近的值。

结论

在本文中,我们将了解 numpy 库的基础知识,使用 array() 函数创建数组,以及其他一些函数,例如absolute() 和 argmin() 来查找 numpy 数组中最接近的值。我希望您能理解并喜欢这篇文章。

参考

  • 这是numpy.argmin 函数的numpy 文档,该函数查找数组中最小值的索引。
  • 请查看NumPy 绝对函数的文档,该函数返回给定数字或数组的绝对值。