Harry Spratt
Harry Spratt

Reputation: 305

Find the last occurrence of the max value in a 2D array

I am trying to find the last occurring max value in an array. The following code is what I have thus far:

a = np.matrix([[1, 2, 3, 4, 5], [99, 7, 8, 9, 10], [99, 12, 13, 99, 15], [16, 99, 18, 19, 20], [99, 22, 23, 24, 99]])
m, n = a.shape
out = np.full((n), np.nan)

for i in range(n):
    out[i] = np.argwhere(a[:, i] == 99)

However it keeps on popping up with an error as shown:

The aim of this code is to go through each column and find the last occurrence of the maximum value ( in this case 99 ) so the result should look something like [4, 3, 0, 2, 4]

Thanks in advance

enter image description here

Upvotes: 2

Views: 998

Answers (3)

you can use argmax, but you must reverse the array order and the subtract it from the array item count -1. argmax finds the index of the first max occurrence.

a = np.matrix([[1, 2, 3, 4, 5], [99, 7, 8, 9, 10], [99, 12, 13, 99, 15], [16, 99, 18, 19, 20], [99, 22, 23, 24, 99]])

out = np.full((n), np.nan)
val = np.full((n), np.nan)

for i in range(n):
     col=a[:,i]
     #argmax finds the max first occurrence, so reverse the col
     col=col[::-1]
     index = len(col) - np.argmax(col) - 1
     val[i]=a[index,i]
     out[i] = index

 print(out)

output:

 [4. 3. 4. 2. 4.]

Upvotes: 1

orlp
orlp

Reputation: 117651

No loop is necessary.

argmax by default finds the first index of the maximum element, but we can use flip to change that. It also by default finds the maximum of the entire multidimensional array, but if passed an axis it will only do it on that axis:

out = a.shape[1] - 1 - np.argmax(np.flip(a, axis=1), axis=1)
out = np.array(out).ravel()

Upvotes: 3

badger
badger

Reputation: 3246

you are close

for i in range(n):
    # first find max value and then the indexes of that value
    z = np.argwhere(a[:, i] == np.amax(a[:, i]))
    w, _ = z.shape
    # extract the position of last max value
    out[i] = z[w - 1, 0]

Upvotes: 1

Related Questions