首頁  >  文章  >  後端開發  >  python中找出numpy array數組的最值及其索引方法

python中找出numpy array數組的最值及其索引方法

不言
不言原創
2018-04-17 10:49:594992瀏覽

下面要為大家分享一篇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))

相關推薦:

怎麼取numpy陣列指定行列

怎麼用numpy找出陣列裡最大與最小值

以上是python中找出numpy array數組的最值及其索引方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn