如何沿第二个轴获取给定 NumPy 数组的最小值和最大值?
让我们看看如何沿第二个轴获取给定 NumPy 数组的最小值和最大值。在这里,第二个轴表示逐行。
我们使用 NumPy 的numpy.amax()和numpy.amin()函数分别获取数组沿第二个轴的最小值和最大值。
numpy.amax():此函数返回数组的最大值或沿轴的最大值(如果提到)。
Syntax: numpy.amax(a, axis=None, out=None, keepdims=
numpy.amin():此函数返回数组的最小值或沿轴的最小值(如果提到)。
Syntax: numpy.amin(a, axis=None, out=None, keepdims=
现在,让我们看一个例子:
示例 1:
Python3
# Import numpy library
import numpy as np
# Create a numpy array
arr = np.array([[0, 1],
[2, 3]])
print("Given Array:\n",
arr)
# find row-wise max values
rslt1 = np.amax(arr, 1)
print("\nMaximum Value:",
rslt1)
# find row-wise min values
rslt2 = np.amin(arr, 1)
print("\nMinimum Value:",
rslt2)
Python3
# Import numpy library
import numpy as np
# Create a numpy array
arr = np.array([[10, 34, 45],
[22, -3, 46],
[33, 4, 6]])
print("Given array:\n",
arr)
# find row-wise max values
rslt1 = np.amax(arr, 1)
print("\nMaximum value along the second axis:",
rslt1)
# find row-wise min values
rslt2 = np.amin(arr, 1)
print("\nMinimum value along the second axis:",
rslt2)
输出:
Given Array:
[[0 1]
[2 3]]
Maximum Value: [1 3]
Minimum Value: [0 2]
示例 2:
Python3
# Import numpy library
import numpy as np
# Create a numpy array
arr = np.array([[10, 34, 45],
[22, -3, 46],
[33, 4, 6]])
print("Given array:\n",
arr)
# find row-wise max values
rslt1 = np.amax(arr, 1)
print("\nMaximum value along the second axis:",
rslt1)
# find row-wise min values
rslt2 = np.amin(arr, 1)
print("\nMinimum value along the second axis:",
rslt2)
输出:
Given array:
[[10 34 45]
[22 -3 46]
[33 4 6]]
Maximum value: [45 46 33]
Minimum value: [10 -3 4]