NumPy 查找数组中的最大和最小元素
使用著名的开源Python库NumPy进行数值计算。支持大型多维数组和矩阵,并且提供大量复杂的数学运算,可用于有效处理这些数组。
在使用NumPy数组时,经常需要查找最大和最小元素。
方法1:使用max()和min()函数
下面的代码示例演示了创建一个整数数组。然后,我们使用max()和min()函数分别找到数组中最高和最低值的元素。
步骤
- 导入所需的NumPy库。
-
创建一个带有整数统计数据的一维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
方法2:使用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
方法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
方法4: 使用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()函数适用于一维和多维数组。然而,与其他方法相比,它们的速度较慢,并且需要更多的内存来存储数组。