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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

lyshello123   2021-03-28 我要评论
想了解python中找出numpy array数组的最值及其索引方法的相关内容吗,lyshello123在本文为您仔细讲解python中找出numpy array数组的最值及其索引的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点: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))

以上这篇python中找出numpy array数组的最值及其索引方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们