网络编程
位置:首页>> 网络编程>> Python编程>> python中找出numpy array数组的最值及其索引方法

python中找出numpy array数组的最值及其索引方法

作者:lyshello123  发布时间:2022-11-26 14:24:00 

标签:python,numpy,数组,最值,索引

在list列表中,max(list)可以得到list的最大值,list.index(max(list))可以得到最大值对应的索引

但在numpy中的array没有index方法,取而代之的是where,其又是list没有的

首先我们可以得到array在全局和每行每列的最大值(最小值同理)


>>> a = np.arange(9).reshape((3,3))
>>> a
array([[0, 1, 2],
 [9, 4, 5],
 [6, 7, 8]])
>>> print(np.max(a))  #全局最大
8
>>> print(np.max(a,axis=0)) #每列最大
[6 7 8]
>>> print(np.max(a,axis=1)) #每行最大
[2 5 8]

然后用where得到最大值的索引,返回值中,前面的array对应行数,后者对应列数


>>> print(np.where(a==np.max(a)))
(array([2], dtype=int64), array([2], dtype=int64))
>>> print(np.where(a==np.max(a,axis=0)))
(array([2, 2, 2], dtype=int64), array([0, 1, 2], dtype=int64))

如果array中有相同的最大值,where会将其位置全部给出


>>> a[1,0]=8
>>> a
array([[0, 1, 2],
 [8, 4, 5],
 [6, 7, 8]])
>>> print(np.where(a==np.max(a)))
(array([1, 2], dtype=int64), array([0, 2], dtype=int64))

来源:https://blog.csdn.net/songyunli1111/article/details/79322103

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com