How to Remove largest Element From a NumPy Array?

This tutorial will discuss about unique ways to remove largest element from a numpy array.

Using numpy.argmin() function

Suppose we have a numpy array of numbers,

numbers = np.array([76, 75, 78, 61, 56, 71, 90, 91])

Now, we want to delete largest element from this NumPy Array.

For this, We will call the argmax() function of the numpy module to get the index position of the largest element of the number array.

# get the index of largest element in array
largestIndex = np.argmax(numbers)

Then we can use the numpy.delete() function to delete the element at this index position i.e. Basically the largest element from this array.

# Remove the largest element
numbers = np.delete(numbers, largestIndex)

It will return a copy of numpy array, after deleting the largest element from the array.

Let’s see the complete example,

import numpy as np

# Create a NumPy Array
numbers = np.array([76, 75, 78, 61, 56, 71, 91, 90])

# get the index of largest element in array
largestIndex = np.argmax(numbers)

# Remove the largest element
numbers = np.delete(numbers, largestIndex)

# Pring NumPy Array
print(numbers)

Output

[76 75 78 61 56 71 90]

Using numpy.argsort()

Call the numpy.argsort() function to get indexes of numpy array in sorted order. Then select the last index position (i.e. -1) from these indices and remove element at that index. Basically it will remove the largest element from numpy array.

Let’s see the complete example,

import numpy as np

# Create a NumPy Array
numbers = np.array([76, 75, 78, 61, 56, 71, 91, 90])

# Get the indices of sorted array
sortedIndices = np.argsort(numbers)

# Delete the element pointed by last index of sorted array
# basically delete the largest element from array
numbers = np.delete(numbers, sortedIndices[-1])

# Pring NumPy Array
print(numbers)

Output

[76 75 78 61 56 71 90]

Summary

We learned about two ways to delete largest element from a NumPy Array in Python.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top