amax()
函数在指定轴上计算数组的最大值。
示例
import numpy as np
array1 = np.array([5, 2, 8, 1, 9])
# find maximum value in array1
maxValue = np.amax(array1)
print(maxValue)
# Output: 9
amax() 语法
amax()
的语法是
numpy.amax(a, axis = None, keepdims = False)
amax() 参数
amax()
函数接受以下参数
a
- 输入数组axis
(可选) - 计算最大值的轴keepdims
(可选) - 是否保留输入数组的维度 (bool
)
amax() 返回值
amax()
函数返回数组中的最大元素或沿指定轴的最大元素。
示例 1:带 2-D 数组的 amax()
axis
参数定义了我们如何在 2-D 数组中找到最大元素。
- 如果
axis
=None
,则数组将被展平,并返回展平后数组的最大值。 - 如果
axis
= 0,则按列计算最大值。 - 如果
axis
= 1,则按行计算最大值。
import numpy as np
array1 = np.array([[10, 17, 25],
[15, 11, 22]])
# calculate the maximum value of the flattened array
result1 = np.amax(array1)
print('The maximum value of the flattened array:', result1)
# calculate the column-wise maximum values
result2 = np.amax(array1, axis=0)
print('Column-wise maximum values (axis 0):', result2)
# calculate the row-wise maximum values
result3 = np.amax(array1, axis=1)
print('Row-wise maximum values (axis 1):', result3)
输出
The maximum value of the flattened array: 25 Column-wise maximum values (axis 0): [15 17 25] Row-wise maximum values (axis 1): [25 22]
这里,
np.amax(array1)
计算展平后数组的最大值。它返回整个数组中的最大元素。np.amax(array1, axis=0)
计算按列的最大值。它返回一个包含每列最大值的数组。np.amax(array1, axis=1)
计算按行的最大值。它返回一个包含每行最大值的数组。
示例 2:带 keepdims 的 amax()
当 keepdims = True
时,结果数组的维度与输入数组的维度匹配。
import numpy as np
array1 = np.array([[10, 17, 25],
[15, 11, 22]])
print('Dimensions of original array:', array1.ndim)
result = np.amax(array1, axis=1)
print('\nWithout keepdims:')
print(result)
print('Dimensions of array:', result.ndim)
# set keepdims to True to retain the dimension of the input array
result = np.amax(array1, axis=1, keepdims=True)
print('\nWith keepdims:')
print(result)
print('Dimensions of array:', result.ndim)
输出
Dimensions of original array: 2 Without keepdims: [25 22] Dimensions of array: 1 With keepdims: [[25] [22]] Dimensions of array: 2
没有 keepdims
时,结果只是一个一维数组,其中包含沿指定轴的最大值。
使用 keepdims
时,结果数组具有与输入数组相同的维度数。