# Python numpy.argmax()

Suraj Joshi 2023年1月30日

Python Numpy `numpy.argmax()` 返回给定 NumPy 数组中具有最大值的索引。

## `numpy.argmax()` 的语法

``````numpy.argmax(a, axis=None, out=None)
``````

### 参数

`a` 可以转换为数组的数组或对象，我们需要在其中找到最高值的索引。
`axis` 沿着行(`axis=0`)或列(`axis=1`)查找最大值的索引。默认情况下，通过对数组进行展平可以找到最大值的索引。
`out` `np.argmax` 方法结果的占位符。它必须有适当的大小以容纳结果。

## 示例代码: `numpy.argmax()` 寻找数组中最大值的索引的方法

### 找出一维数组中最高值的索引

``````import numpy as np

a=np.array([2,6,1,5])

print("Array:")
print(a)

req_index=np.argmax(a)
print("\nIndex with the largest value:")
print(req_index)

print("\nThe largest value in the array:")
print(a[req_index])
``````

``````Array:
[2 6 1 5]

Index with the largest value:
1

The largest value in the array:
6
``````

``````import numpy as np

a=np.array([2,6,1,6])

print("Array:")
print(a)

req_index=np.argmax(a)
print("\nIndex with the largest value:")
print(req_index)

print("\nThe largest value in the array:")
print(a[req_index])
``````

``````Array:
[2 6 1 5]

Index with the largest value:
1

The largest value in the array:
6
``````

### 寻找二维数组中最高值的索引

``````import numpy as np

a=np.array([[2,1,6],
[7,4,5]])

print("Array:")
print(a)

req_index=np.argmax(a)
print("\nIndex with the largest value:")
print(req_index)
``````

``````Array:
[[2 1 6]
[7 4 5]]

Index with the largest value:
3
``````

## 示例代码: 在 `numpy.argmax()` 方法中设置 `axis` 参数以查找数组中最大值的索引

### 沿着列轴寻找最高元素的索引

``````import numpy as np

a=np.array([[2,1,6],
[7,4,5]])

print("Array:")
print(a)

req_index=np.argmax(a,axis=0)
print("\nIndices with the largest value along column axis:")
print(req_index)
``````

``````Array:
[[2 1 6]
[7 4 5]]

Index with the largest value:
[1 1 0]
``````

### 沿着行轴查找最高元素的索引

``````import numpy as np

a=np.array([[2,1,6],
[7,4,5]])

print("Array:")
print(a)

req_index=np.argmax(a,axis=1)
print("\nIndices with the largest value along row axis:")
print(req_index)
``````

``````Array:
[[2 1 6]
[7 4 5]]

Indices with the largest value along the row axis:
[2 0]
``````

## 示例代码：在 `numpy.argmax()` 方法中设置 `out` 参数查找数组中最大值的索引

``````import numpy as np

a=np.array([[2,1,6],
[7,4,5]])

req_index=np.array(0)

print("Array:")
print(a)

np.argmax(a,out=req_index)
print("\nIndex with the largest value:")
print(req_index)
``````

``````Array:
[[2 1 6]
[7 4 5]]

Index with the largest value:
3
``````

Suraj Joshi is a backend software engineer at Matrice.ai.