在許多情況下,數組的大小太大,從它們中找到最大元素需要太多時間。為此,Python 的 numpy 模塊提供了一個名為 numpy.argmax() 的函數。此函數返回與指定軸一起返回的最大值的索引。

用法:
numpy.argmax(a, axis=None, out=None)
參數
x:數組
該參數定義了我們想知道其最大值的源數組。
軸:整數(可選)
該參數定義了索引所在的軸,默認情況下,它進入扁平數組。
輸出:數組(可選)
此參數定義將要插入結果的 ndarray。這將是相同的類型和形狀,適用於存儲結果
返回
此參數定義一個 ndarray,其中包含數組的索引。形狀與 x.shape 相同,隻是移除了沿軸的尺寸。
範例1:
Import numpy as np
x = np.arange(20).reshape(4,5) + 7
x
y=np.argmax(a)
y
輸出:
array([[ 7, 8, 9, 10, 11], [12, 13, 14, 15, 16], [17, 18, 19, 20, 21], [22, 23, 24, 25, 26]]) 19
在上麵的代碼中
- 我們已經導入了別名為 np.
- 我們使用 np.arange() 函數創建了一個四行五列的數組 'x'。
- 我們還在數組的每個元素中添加了 7。
- 我們已經聲明了變量 'y' 並分配了 np.argmax() 函數的返回值。
- 我們已經在函數中傳遞了數組 'x'。
- 最後,我們嘗試打印 'y' 的值。
在輸出中,它顯示了數組中最大元素的索引。
範例2:
Import numpy as np
x = np.arange(20).reshape(4,5) + 7
y=np.argmax(x, axis=0)
z=np.argmax(x, axis=1)
y
z
輸出:
array([3, 3, 3, 3, 3], dtype=int64) array([4, 4, 4, 4], dtype=int64)
範例3:
Import numpy as np
x = np.arange(20).reshape(4,5) + 7
indices = np.unravel_index(np.argmax(x, axis=None), x.shape)
indices
x[indices]
輸出:
(3, 4) 26
範例4:
import numpy as np
a = np.array([[5,2,1], [3,7,9],[0, 4, 6]])
index_arr = np.argmax(a, axis=-1)
index_arr
# Same as np.max(a, axis=-1, keepdims=True)
result = np.take_along_axis(a, np.expand_dims(index_arr, axis=-1), axis=-1)
result1
# Same as np.max(a, axis=-1)
result = np.take_along_axis(a, np.expand_dims(index_arr, axis=-1), axis=-1).squeeze(axis=-1)
result2
輸出:
array([[0], [2], [2]]) array([5, 9, 6])
在上麵的代碼中
- 我們已經導入了別名為 np.
- 我們使用 np.array() 函數創建了一個多維數組 'a'。
- 我們已經聲明了變量 'index_arr' 並分配了 np.argmax() 函數的返回值。
- 我們已經在函數中傳遞了數組 'a' 和軸。
- 我們嘗試打印 'index_arr' 的值。
- 最後,我們嘗試借助兩種不同的方式來獲取數組的最大值,這與 np.argmax() 非常相似。
在輸出中,它顯示了數組中最大元素的索引以及該索引上存在的值。
相關用法
- Python numpy.argmax()用法及代碼示例
- Python numpy.argmin()用法及代碼示例
- Python numpy.argwhere()用法及代碼示例
- Python numpy.argsort()用法及代碼示例
- Python numpy.argpartition()用法及代碼示例
- Python numpy.arccosh()用法及代碼示例
- Python numpy.arcsinh()用法及代碼示例
- Python numpy.array_repr()用法及代碼示例
- Python numpy.array_str()用法及代碼示例
- Python numpy.arctan()用法及代碼示例
- Python numpy.around()用法及代碼示例
- Python numpy.array()用法及代碼示例
- Python numpy.arccos()用法及代碼示例
- Python numpy.arcsin()用法及代碼示例
- Python numpy.array_split()用法及代碼示例
- Python numpy.array_equal()用法及代碼示例
- Python numpy.arctan2()用法及代碼示例
- Python numpy.array_equiv()用法及代碼示例
- Python numpy.arange()用法及代碼示例
- Python numpy.atleast_2d()用法及代碼示例
注:本文由純淨天空篩選整理自 numpy.argmax in Python。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。