This tutorial will discuss about unique ways to remove smallest element from a numpy array.
Table of Contents
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 smallest element from this NumPy Array.
For this, We will call the argmin() function of the numpy module to get the index position of the smallest element of the number array.
# Get the index of smallest element in array smallestIndex = np.argmin(numbers)
Then we can use the numpy.delete() function to delete the element at this index position i.e. basically the smallest element from this array.
# Remove the smallest element numbers = np.delete(numbers, smallestIndex)
It will return a copy of numpy array, after deleting the smallest element from the array.
Let’s see the complete example,
Frequently Asked:
- How to remove multiple elements from a NumPy array?
- Delete elements from a Numpy Array by value or conditions in Python
- Remove Columns with NaN values from a NumPy Array
- How to Remove largest Element From a NumPy Array?
import numpy as np # Create a NumPy Array numbers = np.array([76, 75, 78, 61, 56, 71, 90, 91]) # get the index of smallest element in array smallestIndex = np.argmin(numbers) # Remove the smallest element numbers = np.delete(numbers, smallestIndex) # Pring NumPy Array print(numbers)
Output
[76 75 78 61 71 90 91]
Using numpy.argsort()
Call the numpy.argsort() function to get indexes of numpy array in sorted order. Then select the first index position from these indices and remove element at that index. basically it will remove the smallest 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, 90, 91]) # Get the indices of sorted array sortedIndices = np.argsort(numbers) # Delete the element pointed by first index of sorted array # basically delete the smallest element from array numbers = np.delete(numbers, sortedIndices[0]) # Pring NumPy Array print(numbers)
Output
[76 75 78 61 71 90 91]
Summary
We learned about two ways to delete smallest element from a NumPy Array in Python.