[英]Find first maximum value in a 2d array - Python
I am using a nested for loop to find the coordinates of the maximum value in a 2d array, like the one in the example.我正在使用嵌套的 for 循环来查找 2d 数组中最大值的坐标,就像示例中的那样。 In case the value is repeated the loop breaks after the first one is found.
如果该值重复,则在找到第一个值后循环中断。 It works like this, but I am not good at writing code and I need a more efficient way to do it, because when the 2d array is big (let's say a (880x1024 matrix)) it takes long time to find the value.
它的工作原理是这样的,但我不擅长编写代码,我需要一种更有效的方法来做到这一点,因为当二维数组很大时(比如说一个(880x1024 矩阵)),找到值需要很长时间。 Any suggestions?
有什么建议么? Is there a much easier way to find the coordinates I need?
有没有更简单的方法来找到我需要的坐标?
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
Try this -尝试这个 -
arr.max()
arr.max()
获得最大值unravel()
the array into a flat 1D, find the first index in this array using np.argmax()
which returns index of only the first occurance.unravel()
转换为平面一维,使用np.argmax()
查找此数组中的第一个索引,该索引仅返回第一次出现的索引。unravel_index
to get the index of the flat index as it would be if the array was 3D and of the shape of the original example.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.