NumPy argmax()

argmax() 方法返回数组中最大元素的索引。

示例

import numpy as np
array1 = np.array([10, 12, 14, 11, 5])

# return index of largest element (14) maxIndex= np.argmax(array1)
print(maxIndex) # Output: 2

argmax() 语法

argmax() 的语法是:

numpy.argmax(array, axis = None, out = None, keepdims = <no value>)

argmax() 参数

argmax() 方法接受四个参数:

  • array - 输入数组
  • axis (可选) - 返回索引的轴 (int)
  • out (可选) - 用于存储输出的数组
  • keepdims (可选) - 是否保留输入数组的维度 (bool)

argmax() 返回值

argmax() 方法返回最大元素的索引。


示例 1:字符串的 argmax()

argmax() 方法与 stringchar 数组一起使用时,将根据 ASCII 值返回最大元素的索引。

import numpy as np

array = np.array(['A', 'B', 'G', 'D', 'C'])

# return index of max element 'G' maxIndex = np.argmax(array)
print(maxIndex)

输出

2

示例 2:二维数组的 argmax()

axis 参数定义了我们如何处理二维数组中最大元素的索引。

  • 如果 axis = None,数组将被展平,并返回展平后数组的索引。
  • 如果 axis = 0,将返回每列中最大元素的索引。
  • 如果 axis = 1,将返回每行中最大元素的索引。
import numpy as np

array = np.array([[10, 17, 25], [15, 11, 22]])
                  
# return the index of the largest element of the flattened array maxIndex = np.argmax(array)
print('Index of the largest element in the flattened array: ', maxIndex)
# return the index of the largest element in each column maxIndex = np.argmax(array, axis = 0)
print('Index of the largest element in each row (axis 0): ', maxIndex)
# return the index of the largest element in each row maxIndex = np.argmax(array, axis = 1)
print('Index of the largest element in each row (axis 1): ', maxIndex)

输出

Index of the largest element in the flattened array:  2
Index of the largest element in each row (axis 0):  [1 0 0]
Index of the largest element in each row (axis 1):  [2 2]

示例 3:带 'out' 数组的 argmax()

在我们之前的示例中,argmax() 函数生成了一个新的输出数组。

但是,我们可以使用 out 参数使用现有数组来存储输出。

import numpy as np

array1 = np.array([[10, 17, 25], 
                   [15, 11, 22], 
                   [11, 19, 20]])

# create an empty array
array2= np.array([0, 0, 0])

# pass the 'out' argument to store the result in array2 np.argmax(array1, axis = 0, out = array2)
print(array2)

输出

[1 2 0]

示例 4:带 keepdims 的 argmax()

keepdims = True 时,结果数组的维度与输入数组的维度匹配。

import numpy as np

array1 = np.array([[10, 17, 25], [15, 11, 22]])
print('Shape of original array: ', array1.shape)

maxIndex = np.argmax(array1, axis = 1)
print('\n Without keepdims: \n', maxIndex) print('Shape of array: ', maxIndex.shape)
# set keepdims to True to retain the dimension of the input array maxIndex = np.argmax(array1, axis = 1, keepdims = True)
print('\n With keepdims: \n', maxIndex) print('Shape of array: ', maxIndex.shape)

输出

Shape of original array:  (2, 3)

Without keepdims: 
[2 2]
Shape of array: (2,)

With keepdims: 
[[2]
[2]]
Shape of array: (2, 1)

如果不使用 keepdims,结果只是一个包含索引的一维数组。

使用 keepdims 时,结果数组具有与输入数组相同的维度数。

同样,当 axis = 1keepdims = True 时,结果数组具有与输入数组相同的行数,但其列只有一个元素,即该列中最大元素的索引。

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战