在 NumPy 数组中查找最大和最小元素


著名的开源 Python 库 NumPy 用于数值计算。它支持大型多维数组和矩阵,以及大量可用于有效处理这些数组的复杂数学运算。

在使用 NumPy 数组时,经常需要查找最大和最小元素。

方法一:使用 max() 和 min() 函数

以下代码演示了创建整数数组的过程。然后,我们分别使用 max() 和 min() 函数查找数组中最大和最小的元素。

算法

  • 导入所需的 Numpy 库。

  • 创建一个包含整数数据的 1D numpy 数组。

  • 使用 max() 和 min() 函数查找最大和最小元素。

  • 打印结果。

示例

# Import numpy library
import numpy as np
arry = np.array([69, 96, 99, 14, 3])

# Finding the maximum element
max_elent = np.max(arry)

# Finding the maximum element
min_elent = np.min(arry)

print("max element in the array is:", max_elent)
print("min element in the array is:", min_elent)

输出

Max element in the array is: 99
Min element in the array is: 3

方法二:在 NumPy 中使用 Argmax() 和 Argmin() 函数

以下代码演示了如何使用 argmax() 和 argmin() 函数在给定数组中查找最小和最大元素。

算法

  • 导入 numpy 库。

  • 创建一个包含整数数据的 numpy 数组。

  • 获取最大和最小元素的索引。

  • 获取最大和最小元素及其索引。

  • 打印信息。

示例

import numpy as npy
ary = npy.array([2023, 56, 400, 2025, 3])

# fetching index of the maximum and minimum element
max_idx = npy.argmax(ary)
min_idx = npy.argmin(ary)

# Get the maximum and minimum element
max_elnt = ary[max_idx]
min_elnt = ary[min_idx]

print("Max_element in the array is:", max_elnt)
print("Min_element in the array is:", min_elnt)

输出

Max_element in the array is: 2025
Min_element in the array is: 3

方法三:使用 sort() 方法

在本例中,我们将创建一个包含一些整数的 numpy 数组。使用 sort() 方法对数组的元素进行排序,然后我们可以从排序后的数组的首尾索引获取最小和最大元素。

算法

  • 导入 numpy 库。

  • 创建一个包含随机元素的 numpy 数组。

  • 使用 sort() 方法对数组进行排序。

  • 通过访问第一个元素可以得到数组中最小的元素。

  • 通过访问最后一个元素可以得到数组中最大的元素。

  • 打印信息。

示例

import numpy as npy
ary = npy.array([420, 99, 840, 366, 9])
ary.sort()

# Get the minimum and maximum element after sorting
min_elnt = ary[0]
max_elnt = ary[-1]

print("max_ele in the array is:", min_elnt)
print("min_ele in the array is:", max_elnt)

输出

max_ele in the array is: 9
min_ele in the array is: 840

方法四:使用 Amax() 和 Amin() 函数

在这个例子中,我们将创建一个二维 NumPy 数组,并使用 amax() 和 amin() 函数查找数组的最大和最小元素。

算法

  • 导入 numpy 库。

  • 初始化一个二维 numpy 数组。

  • 使用 amax() 和 amin() 函数分别确定数组中的最大和最小元素。

  • 显示所需的信息。

import numpy as nmp
ary = nmp.array([[17, 23, 53], [466, 5, 76]])

# Finding max and min element
max_elnt = nmp.amax(ary)
min_elnt = nmp.amin(ary)

print("max element in the array is:", max_elnt)
print("min element in the array is:", min_elnt)

输出

max element in the array is: 466
min element in the array is: 5

结论

max() 和 min() 函数对于处理大型数据高效且直接,但它们不提供元素索引。

amax() 和 amin() 函数适用于一维和多维数组。但是,与其他方法相比,它速度较慢,需要更多内存来存储数组。

更新于:2023年8月23日

1K+ 次浏览

开启您的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.