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

yipeiwu_com5年前Python基础

在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数组的最值及其索引方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

go和python变量赋值遇到的一个问题

平时写得多的是python,最近看了一点go,今天碰到了一个问题,和大家分享一下 package main import "fmt" type student struct {...

Python利用Django如何写restful api接口详解

Python利用Django如何写restful api接口详解

前言 用Python如何写一个接口呢,首先得要有数据,可以用我们在网站上爬的数据,在上一篇文章中写了如何用Python爬虫,有兴趣的可以看看:/post/141661.htm 大量的数...

python学习开发mock接口

本文实例为大家分享了python学习开发mock接口的具体步骤,供大家参考,具体内容如下 #1.测试为什么要开发接口? 1)在别的接口没有开发好的时候, mock接口(模拟接口) 2)...

Python 编码规范(Google Python Style Guide)

Python 风格规范(Google) 本项目并非 Google 官方项目, 而是由国内程序员凭热情创建和维护。 如果你关注的是 Google 官方英文版, 请移步 Googl...

Python备份目录及目录下的全部内容的实现方法

本来是想写一个东西可以直接调用TortoiseSVN保存当前代码到一个分枝下的。 可惜调用SVN的部分还在研究。就先写了目录拷贝的部分。 如果有喜欢研究Python的童鞋愿意提供想法或者...