简体   繁体   中英

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

Try this -

  1. You can get max value simply with arr.max()
  2. 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 using np.argmax() which returns index of only the first occurance.
  3. Then you can 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.
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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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