繁体   English   中英

在二维数组中查找第一个最大值 - Python

[英]Find first maximum value in a 2d array - Python

我正在使用嵌套的 for 循环来查找 2d 数组中最大值的坐标,就像示例中的那样。 如果该值重复,则在找到第一个值后循环中断。 它的工作原理是这样的,但我不擅长编写代码,我需要一种更有效的方法来做到这一点,因为当二维数组很大时(比如说一个(880x1024 矩阵)),找到值需要很长时间。 有什么建议么? 有没有更简单的方法来找到我需要的坐标?

example = np.array([[10, 20, 30], [40, 50, 60], [70, 101, 90], [101, 101, 101], [61, 62, 101], [71, 72, 73]])
count_i = 0
count_j = 0
for i in example:
    count_i += 1
    for j in i:
        count_j += 1
        if j == np.max(example):
            print('value found', j)
            print('row coordinate', count_i)
            col = matrix.shape[1] - ((matrix.shape[1] * count_i) - count_j)
            print('colum coordinate', col)
            break
    else:
        continue
    break

尝试这个 -

  1. 您可以简单地使用arr.max()获得最大值
  2. 要获取最大值第一次出现的索引,您可以将数组 unravel( unravel()转换为平面一维,使用np.argmax()查找此数组中的第一个索引,该索引仅返回第一次出现的索引。
  3. 然后,您可以unravel_index获取平面索引的索引,就像数组是 3D 和原始示例的形状一样。
example = np.array([[10, 20, 30], 
                    [40, 50, 60], 
                    [70, 101, 90], 
                    [101, 101, 101], 
                    [61, 62, 101], 
                    [71, 72, 73]])

maxvalue = example.max()

idx_flat = example.ravel().argmax()
idx = np.unravel_index(idx_flat, example.shape)

print('max value:',maxvalue)
print('first location:', idx)
max value: 101
first location: (2, 1)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM