Find the kth maximum element in a NumPy array

Learn, how to find the kth maximum element in a NumPy array? By Pranit Sharma Last updated : December 28, 2023

NumPy Array: Finding the kth maximum element

For example, if we are given an array [1,2,3,4,5] and we need the third maximum element in this array i.e., 3.

To find the kth maximum element in a NumPy array, we can just sort the numpy array and index the array with k-1 and the result will be the kth maximum element.

Use the below code statement for this:

# Finding 3rd maximum element
res = arr[np.argsort(arr)][k-1]

Let us understand with the help of an example,

Python code to find the kth maximum element in a NumPy array

# Import numpy
import numpy as np

# Creating a numpy array
arr = np.array([1,53,12,24,35,63])

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

# Defining k
k = 3

# Finding 3rd maximum element
res = arr[np.argsort(arr)][k-1]

# Display result
print(res)

Output

Example: Find the kth maximum element in a NumPy array

In this example, we have used the following Python basic topics that you should learn:

Python NumPy Programs »

Comments and Discussions!

Load comments ↻





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