Find Last Occurrence of Maximum Value in a numpy.ndarray()

In this tutorial, we will learn how to find the last occurrence of the maximum value in a numpy.ndarray() in Python? By Pranit Sharma Last updated : May 13, 2023

Suppose that we are given a NumPy ndarray in which the maximum value will mostly occur more than once and we need to find a way to find the index of the last occurrence of the maximum value. Note that, we want to find only the index of the last occurrence, not an array of all occurrences.

How to find last occurrence of maximum value in a numpy.ndarray()?

To find the last occurrence of the maximum value in a numpy.ndarray(), reverse the array inside the argmax() method to get the index of the max value, and then subtract it from the length of the array. The following code statement is used for this:

res = len(arr) - np.argmax(rev) -1

Let us understand with the help of an example,

Python program to find last occurrence of maximum value in a numpy.ndarray()

# Import numpy
import numpy as np

# Creating an array
arr = np.array([0, 0, 4, 4, 4, 4, 2, 2, 2, 2])

# Display original array
print("Original array:\n", arr, "\n")

# Reversing the array
rev = arr[::-1]

# Max value of last occurrence
res = len(arr) - np.argmax(rev) - 1

# Display result
print("Last occurrence of max value is at index:\n", res, "\n")

Output

Original array:
 [0 0 4 4 4 4 2 2 2 2] 

Last occurrence of max value is at index:
 5 

Python NumPy Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.