Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

numpy
python
communitycreator

How to get indices of N maximum values in NumPy arrays

Harsh Jain

Introduction

In this shot, we will learn how to find the indices of N maximum values in a NumPy array. We do not have any ready-made function that can give us the indices of N maximum values in a NumPy array. However, we can manipulate existing NumPy functions to suffice our needs. In order to get the indices of N maximum values in a NumPy array, we can use the argsort() function.

Description

The numpy.argsort() function performs an indirect sort along the given axis.

Syntax

The syntax of the argsort() function is as shown below:

numpy.argsort(Numpy_array, axis=None, kind=None, order=None)

Parameter

The numpy.argsort() function accepts the following parameters:

  • Numpy_array: The source array that needs to be sorted.

  • Axis: Defines the axis along which the sorting is performed. A flattened array is used by default.

  • Kind: Defines the sorting algorithm. Kind takes quick-sort by default.

  • Order: Specifies which fields to compare first.

Return value

The numpy.argsort() function returns an array of indices in accordance with the specified axis.

Code

Let’s have a look at the code now.

# Importing the Numpy Package
import numpy as np

# Numpy Array
scores = np.array([100,67,92,87,66,89,76,22])

# Getting indices of N = 3 maximum values
x = np.argsort(scores)[::-1][:3]
print("Indices:",x)

# Getting N maximum values
print("Values:",scores[x])

Explanation

  • In line 2 we import the numpy library with alias np.

  • In line 5 we create a numpy array that needs to be sorted.

  • In line 8 we sort the numpy array with the np.argsort() function. The np.argsort() function sorts the numpy array in ascending order and returns their indices.

    Since the problem statement wants us to find the indices of N maximum numbers, we use [::-1] to reverse the array. Lastly, we use [:N] to get the first N values. Here, N = 3 has been taken.

  • In line 9 we print the required indices.

  • In line 12 we print the N maximum values to check the sanity of the program.

In this way, we can get the indices of N maximum values from a NumPy array. We can also get the indices of N minimum values by not reversing the array. In that case, we wouldn’t use [::-1] in line 8.

RELATED TAGS

numpy
python
communitycreator
RELATED COURSES

View all Courses

Keep Exploring