NumPy argmin()

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

示例

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

# return index of smallest element (5) minIndex = np.argmin(array1)
print(minIndex) # Output: 4

argmin() 语法

argmin() 的语法是

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

argmin() 参数

argmin() 方法接受四个参数

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

argmin() 返回值

argmin() 方法返回最小元素的索引。


示例 1:argmin() 与字符串

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

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

# return index of min element 'A' minArgument = np.argmin(array)
print(minArgument)

输出

0

示例 2:argmin() 与二维数组

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 smallest element of the flattened array minIndex = np.argmin(array)
print('Index of the smallest element in the flattened array: ', minIndex)
# return the index of the smallest element in each column minIndex = np.argmin(array, axis = 0)
print('Index of the smallest element in each column (axis 0): ', minIndex)
# return the index of the smallest element in each row minIndex = np.argmin(array, axis = 1)
print('Index of the smallest element in each row (axis 1): ', minIndex)

输出

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

示例 3:argmin() 与 'out' 数组

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

但是,我们可以使用 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.argmin(array1, axis = 0, out = array2)
print(array2)

输出

[0 1 2]

示例 4:argmin() 与 keepdims

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

import numpy as np

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

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

输出

Shape of original array:  (2, 3)

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

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

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

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

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

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

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

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