使用numpy寻找【二维数组】中的最值及其下标

一、通过np.max和np.where寻找【所有满足条件的解】 通过np.max()找矩阵的最大值,再通过np.where获得最大值的位置,代码如下:

import numpy as npa = np.random.randint(1, 10, size=12) a = a.reshape((3,4))print(a) print(np.max(a))r, c = np.where(a == np.max(a)) print(r,c)

输出:
[[7 8 9 4] [9 3 9 3] [5 6 1 5]]9 [0 1 1] [2 0 2]

输出的是两个array,分别是x和y数组,即找出了和这个最值相等的所有位置。
二、通过np.argmax寻找【第一个满足条件的解】 把矩阵展成一维,np.argmax可以返回最大值在这个一维数组中第一次出现的位置,用这个位置除以矩阵的列数,所得的商就是最大值所在的行,所得的余数就是最大值所在的列。
import numpy as npa = np.random.randint(1, 10, size=12) a = a.reshape((3,4))print(a) print(np.max(a))m = np.argmax(a)# 把矩阵拉成一维,m是在一维数组中最大值的下标 r, c = divmod(m, a.shape[1])# r和c分别为商和余数,即最大值在矩阵中的行和列 # m是被除数, a.shape[1]是除数 print(r, c)

输出:
[[5 5 9 7] [5 5 8 9] [2 3 9 3]] 90 2

【使用numpy寻找【二维数组】中的最值及其下标】可以看到只找到了第一个出现的最大值,后续的是搜索不到的。

    推荐阅读