# 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.