在许多情况下,如果数组的大小太大,那么从它们中找到最大元素的时间就太多了。为此,Python的numpy模块提供了一个名为 numpy.argmax()的函数。该函数返回最大值的索引以及指定的轴。
numpy.argmax(a, axis=None, out=None)
x:array_like
此参数定义了我们想要知道其最大值的源数组。
axis:int(可选)
此参数定义沿其存在索引的轴,默认情况下,它位于扁平化数组中。
out:array(可选)
此参数定义要在其中插入结果的ndarray。这将是相同的类型和形状,适合于存储结果
此参数定义一个ndarray,其中包含数组的索引。形状与 x.shape 相同,但沿轴的尺寸已删除。
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
在上面的代码中
在输出中,它显示了数组中最大元素的索引。
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)
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
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])
在上面的代码中
在输出中,它显示了数组中最大元素的索引以及该索引上存在的值。
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)