'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. 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. 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
Solution 1:[1]
Try this -
- You can get max value simply with
arr.max() - To get the index for the first occurrence of max value, you can
unravel()the array into a flat 1D, find the first index in this array usingnp.argmax()which returns index of only the first occurance. - Then you can
unravel_indexto get the index of the flat index as it would be if the array was 3D and of the shape of the original example.
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)
Solution 2:[2]
Try this with numpy.
Get the argument containing the maximum value of a flattened bi-dimensional array with
max_unidimensional_index = np.argmax(bidim_array, axis=None)Map the
max_unidimensional_indexto the original bi-dimensional shape array withnp.unravel
bidim_index = np.unravel_index(max_unidimensional_index, bidim_array.shape)
import numpy as np
bidim_index = np.unravel_index(np.argmax(example, axis=None), example.shape)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Akshay Sehgal |
| Solution 2 | Rodrigo Lopez |
