📌  相关文章
📜  找到最接近的值和 NumPy 数组的索引

📅  最后修改于: 2022-05-13 01:54:34.168000             🧑  作者: Mango

找到最接近的值和 NumPy 数组的索引

在本文中,让我们讨论使用 NumPy 在数组中查找最近值和索引。麻木 提供了一个高性能的多维数组对象,以及用于处理这些数组的工具。我们将利用 NumPy 库提供的众多函数中的两个来计算数组中的最近值和索引。这两个函数是numpy.abs()numpy.argmin() 下面给出了在数组中查找最近值和索引的方法:

方法:

  • 取一个数组,比如 arr[] 和一个元素,比如 x,我们必须找到最接近的值。
  • 调用 numpy.abs(d)函数,将 d 作为数组元素与 x 之间的差值,并将值存储在差值数组中,例如 difference_array[]。
  • 提供最小差异的元素将最接近指定值。
  • 使用 numpy.argmin(),获取差异数组[]中最小元素的索引。在多个最小值的情况下,将返回第一次出现。
  • 打印给定数组中最近的元素及其索引。

让我们看一下基于上述方法的以下示例。

示例 1:

Python3
import numpy as np
  
  
# array
arr = np.array([8, 7, 1, 5, 3, 4])
print("Array is : ", arr)
  
# element to which nearest value is to be found
x = 2
print("Value to which nearest element is to be found: ", x)
  
# calculate the difference array
difference_array = np.absolute(arr-x)
  
# find the index of minimum element from the array
index = difference_array.argmin()
print("Nearest element to the given values is : ", arr[index])
print("Index of nearest value is : ", index)


Python3
import numpy as np
  
  
# array
arr = np.array([12, 40, 65, 78, 10, 99, 30])
print("Array is : ", arr)
  
# element to which nearest value is to be found
x = 85
print("Value to which nearest element is to be found: ", x)
  
# calculate the difference array
difference_array = np.absolute(arr-x)
  
# find the index of minimum element from the array
index = difference_array.argmin()
print("Nearest element to the given values is : ", arr[index])
print("Index of nearest value is : ", index)


输出:

在上面的例子中,我们取了一个数组,我们需要从中找到离指定值最近的元素。指定的值为 2。我们从数组的每个元素中减去给定的值,并将绝对值存储在不同的数组中。最小绝对差将对应于最接近给定数字的值。在我们的例子中,(2-1) 产生 1。因此,最小绝对差的索引是 2,来自原始数组索引 2 的元素是 1。因此,1 最接近给定的数字,即 2。

示例 2:

蟒蛇3

import numpy as np
  
  
# array
arr = np.array([12, 40, 65, 78, 10, 99, 30])
print("Array is : ", arr)
  
# element to which nearest value is to be found
x = 85
print("Value to which nearest element is to be found: ", x)
  
# calculate the difference array
difference_array = np.absolute(arr-x)
  
# find the index of minimum element from the array
index = difference_array.argmin()
print("Nearest element to the given values is : ", arr[index])
print("Index of nearest value is : ", index)

输出:

在上面的例子中,我们取了一个数组,我们需要从中找到离指定值最近的元素。指定的值为 85。我们从数组的每个元素中减去给定的值,并将绝对值存储在不同的数组中。最小绝对差将对应于最接近给定数字的值。在上面的例子中,(78-85) 产生 7。因此,最小绝对差的索引是 3,来自原始数组索引 3 的元素是 78。因此,78 最接近给定的数字,即 85。