📌  相关文章
📜  如何在 NumPy 1d-array 中找到最大值和最小值?

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

如何在 NumPy 1d-array 中找到最大值和最小值?

让我们看看在 NumPy 一维数组中找到最大值和最小值的各种方法。

方法一:使用 NumPy 库的numpy.amax()numpy.amin()函数。

  • numpy.amax():此函数返回数组的最大值或沿轴的最大值(如果提到)。
  • numpy.amin():此函数返回数组的最小值或沿轴的最小值(如果提到)。

例子:

Python3
# import library
import numpy as np
 
# create a numpy 1d-array
array = np.array([1, 2, 3,
                  0, -1, -2])
 
# find max element in an array
max_ele = np.amax(array)
 
# find min element in an array
min_ele = np.amin(array)
 
 
# show the outputs
print("Given Array:", array)
 
print("Max Element:", max_ele)
 
print("Min Element:", min_ele)


Python3
# import library
import numpy as np
 
# create a numpy 1d-array
array = np.array([1, 2, 3,
                  0, -1, -2])
 
# find index of max element
# in an array
max_ele_index = np.argmax(array)
 
# find max element in an array
max_ele = array[max_ele_index]
 
# find index of min element
# in an array
min_ele_index = np.argmin(array)
 
# find min element in an array
min_ele = array[min_ele_index]
 
# show the outputs
print("Given Array:", array)
 
print("Max Element:", max_ele)
 
print("Min Element:", min_ele)


输出:

Given Array: [ 1  2  3  0 -1 -2]
Max Element: 3
Min Element: -2

方法二:使用 NumPy 库的numpy.argmax()numpy.argmin()函数。

  • numpy.argmax():此函数返回特定轴中数组的最大元素的索引(如果提到)。
  • numpy.argmin():此函数返回特定轴中数组的最小元素的索引(如果提到)。

例子:

Python3

# import library
import numpy as np
 
# create a numpy 1d-array
array = np.array([1, 2, 3,
                  0, -1, -2])
 
# find index of max element
# in an array
max_ele_index = np.argmax(array)
 
# find max element in an array
max_ele = array[max_ele_index]
 
# find index of min element
# in an array
min_ele_index = np.argmin(array)
 
# find min element in an array
min_ele = array[min_ele_index]
 
# show the outputs
print("Given Array:", array)
 
print("Max Element:", max_ele)
 
print("Min Element:", min_ele)

输出:

Given Array: [ 1  2  3  0 -1 -2]
Max Element: 3
Min Element: -2