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

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

在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))

Life is short, You need Python~

    原文作者:lyshello123
    原文地址: https://blog.csdn.net/songyunli1111/article/details/79322103
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞