编程语言
首页 > 编程语言> > python中如何找出numpy array数组的最值及其索引?

python中如何找出numpy array数组的最值及其索引?

作者:互联网

转自:微点阅读  https://www.weidianyuedu.com

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

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

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

>>> a = np.arange(9).reshape((3,3))>>> aarray([[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>>> aarray([[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))

标签:python,dtype,print,where,max,np,array,numpy
来源: https://blog.csdn.net/ysds20211402/article/details/123068287