The Wayback Machine - https://web.archive.org/web/20241104172856/https://www.geeksforgeeks.org/finding-the-k-smallest-values-of-a-numpy-array/
Open In App

Finding the k smallest values of a NumPy array

Last Updated : 02 Sep, 2020
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, let us see how to find the k number of the smallest values from a NumPy array.

Examples:

Input: [1,3,5,2,4,6] 
k = 3

Output: [1,2,3] 

Method 1: Using np.sort() . 

Approach:

  1. Create a NumPy array.
  2. Determine the value of k.
  3. Sort the array in ascending order using the sort() method.
  4. Print the first k values of the sorted array.

Python3




# importing the modules
import numpy as np
  
# creating the array 
arr = np.array([23, 12, 1, 3, 4, 5, 6])
print("The Original Array Content")
print(arr)
  
# value of k
k = 4
  
# sorting the array
arr1 = np.sort(arr)
  
# k smallest number of array
print(k, "smallest elements of the array")
print(arr1[:k])


Output:

The Original Array Content
[23 12  1  3  4  5  6]
4 smallest elements of the array
[1 3 4 5]

Method 2: Using np.argpartition() 

Approach:

  1. Create a NumPy array.
  2. Determine the value of k.
  3. Get the indexes of the smallest k elements using the argpartition() method.
  4. Fetch the first k values from the array obtained from argpartition() and print their index values with respect to the original array.

Python3




# importing the module
import numpy as np
  
# creating the array 
arr = np.array([23, 12, 1, 3, 4, 5, 6])
print("The Original Array Content")
print(arr)
  
# value of k
k = 4
  
# using np.argpartition()
result = np.argpartition(arr, k)
  
# k smallest number of array
print(k, "smallest elements of the array")
print(arr[result[:k]])


Output:

The Original Array Content
[23 12  1  3  4  5  6]
4 smallest elements of the array
[4 3 1 5]


Similar Reads

NumPy Array Sorting | How to sort NumPy Array
Sorting an array is a very important step in data analysis as it helps in ordering data, and makes it easier to search and clean. In this tutorial, we will learn how to sort an array in NumPy. You can sort an array in NumPy: Using np.sort() functionin-line sortsorting along different axesUsing np.argsort() functionUsing np.lexsort() functionUsing s
4 min read
Difference between Numpy array and Numpy matrix
While working with Python many times we come across the question that what exactly is the difference between a numpy array and numpy matrix, in this article we are going to read about the same. What is np.array() in PythonThe Numpy array object in Numpy is called ndarray. We can create ndarray using numpy.array() function. It is used to convert a l
3 min read
NumPy ndarray.tolist() Method | Convert NumPy Array to List
The ndarray.tolist() method converts a NumPy array into a nested Python list. It returns the array as an a.ndim-levels deep nested list of Python scalars. Data items are converted to the nearest compatible built-in Python type. Example C/C++ Code import numpy as np gfg = np.array([1, 2, 3, 4, 5]) print(gfg.tolist()) Output[1, 2, 3, 4, 5] SyntaxSynt
1 min read
NumPy ndarray.size() Method | Get Number of Elements in NumPy Array
The ndarray.size() method returns the number of elements in the NumPy array. It works the same as np.prod(a.shape), i.e., the product of the dimensions of the array. Example C/C++ Code import numpy as np arr = np.zeros((3, 4, 2), dtype = np.complex128) gfg = arr.size print (gfg) Output : 24Syntax Syntax: numpy.ndarray.size(arr) Parameters arr : [ar
1 min read
NumPy ndarray.__abs__() | Find Absolute Value of Elements in NumPy Array
The ndarray.__abs__() method returns the absolute value of every element in the NumPy array. It is automatically invoked when we use Python's built-in method abs() on a NumPy array. Example C/C++ Code import numpy as np gfg = np.array([1.45, 2.32, 3.98, 4.41, 5.55, 6.12]) print(gfg.__abs__()) Output[ 1 2 3 4 5 6] SyntaxSyntax: ndarray.__abs__() Ret
1 min read
NumPy ndarray.__ilshift__() | Shift NumPy Array Elements to Left
The ndarray.__ilshift__() method is an in-place left-shift operation. It shifts elements in the array to the left of the number of positions specified. Example C/C++ Code import numpy as np gfg = np.array([1, 2, 3, 4, 5]) # applying ndarray.__ilshift__() method print(gfg.__ilshift__(2)) Output[ 4 8 12 16 20] SyntaxSyntax: ndarray.__ilshift__($self,
1 min read
NumPy ndarray.__irshift__() | Shift NumPy Array Elements to Right
The ndarray.__irshift__() method returns a new array where each element is right-shifted by the value that is passed as a parameter. Example C/C++ Code import numpy as np gfg = np.array([1, 2, 3, 4, 5]) # applying ndarray.__irshift__() method print(gfg.__irshift__(2)) Output[0 0 0 1 1] SyntaxSyntax: ndarray.__irshift__($self, value, /) Parameter se
1 min read
NumPy ndarray.imag() Method | Get Imaginary Part in NumPy Array
The ndarray.imag() method returns the imaginary part of the complex number in the NumPy array. Note: Remember resulting data type for the imaginary value is 'float64'. Example C/C++ Code # import the important module in python import numpy as np # make an array with numpy gfg = np.array([1 + 2j, 2 + 3j]) # applying ndarray.imag() method geeks = np.
1 min read
NumPy ndarray.transpose() Method | Find Transpose of the NumPy Array
The ndarray.transpose() function returns a view of the array with axes transposed. For a 1-D array, this has no effect, as a transposed vector is simply the same vector.For a 2-D array, this is a standard matrix transpose.For an n-D array, if axes are given, their order indicates how the axes are permuted. If axes are not provided and arr.shape = (
2 min read
Calculate the difference between the maximum and the minimum values of a given NumPy array along the second axis
Let's see how to calculate the difference between the maximum and the minimum values of a given NumPy array along the second axis. Here, the Second axis means row-wise. So firstly for finding the row-wise maximum and minimum elements in a NumPy array we are using numpy.amax() and numpy.amin() functions of NumPy library respectively. then After that
2 min read
Convert list of Celsius values into Fahrenheit using NumPy array
Let us see how to convert a list of Celsius temperatures into Fahrenheit by converting them into NumPy array. The formula to convert Celsius to Fahrenheit is : feh = (9 * cel / 5 + 32) Method 1 : Using the numpy.array() method. C/C++ Code # importing the module import numpy as np # taking the celsius input inp = [0, 12, 45.21, 34, 99.91] # storing
2 min read
How to remove NaN values from a given NumPy array?
In this article, we are going to learn how to remove Nan values from a given array. Nan values are those values that do not have a specific value associated with them or they are different from the type of values that are to be used in the declared array. There are basically three approaches with slight differences in syntax. Either we could use a
3 min read
How to get the floor, ceiling and truncated values of the elements of a numpy array?
In this article, let's discuss how to get the floor, ceiling, and truncated values of the elements of a Numpy array. First, we need to import the NumPy library to use all the functions available in it. This can be done with this import statement: import numpy as np Getting the floor value The greatest integer that is less than or equal to x where x
3 min read
How to get the n-largest values of an array using NumPy?
Let's see the program for how to get the n-largest values of an array using NumPy library. For getting n-largest values from a NumPy array we have to first sort the NumPy array using numpy.argsort() function of NumPy then applying slicing concept with negative indexing. Syntax: numpy.argsort(arr, axis=-1, kind=’quicksort’, order=None) Return: [inde
2 min read
How to check whether specified values are present in NumPy array?
Sometimes we need to test whether certain values are present in an array. Using Numpy array, we can easily find whether specific values are present or not. For this purpose, we use the "in" operator. "in" operator is used to check whether certain element and values are present in a given sequence and hence return Boolean values 'True" and "False".
2 min read
How to Remove columns in Numpy array that contains non-numeric values?
Many times we have non-numeric values in NumPy array. These values need to be removed, so that array will be free from all these unnecessary values and look more decent. It is possible to remove all columns containing Nan values using the Bitwise NOT operator and np.isnan() function. Example 1: C/C++ Code # Importing Numpy module import numpy as np
2 min read
How to get values of an NumPy array at certain index positions?
Sometimes we need to remove values from the source Numpy array and add them at specific indices in the target array. In NumPy, we have this flexibility, we can remove values from one array and add them to another array. We can perform this operation using numpy.put() function and it can be applied to all forms of arrays like 1-D, 2-D, etc. Example
4 min read
How to normalize an NumPy array so the values range exactly between 0 and 1?
In this article, we will cover how to normalize a NumPy array so the values range exactly between 0 and 1. Normalization is done on the data to transform the data to appear on the same scale across all the records. After normalization, The minimum value in the data will be normalized to 0 and the maximum value is normalized to 1. All the other valu
3 min read
Rank Values in NumPy Array
When working with data in NumPy arrays, it's often necessary to rank the elements based on certain criteria. Ranking can be useful for tasks like finding the largest or smallest values, identifying outliers, or sorting data for further analysis. In this article, we are going to see how to rank items in Numpy arrays in Python. Rank Items in Python N
4 min read
Appending values at the end of an NumPy array
Let us see how to append values at the end of a NumPy array. Adding values at the end of the array is a necessary task especially when the data is not fixed and is prone to change. For this task, we can use numpy.append() and numpy.concatenate(). This function can help us to append a single value as well as multiple values at the end of the array.
4 min read
How to count the frequency of unique values in NumPy array?
Let's see How to count the frequency of unique values in the NumPy array. Python’s Numpy library provides a numpy.unique() function to find the unique elements and their corresponding frequency in a NumPy array. numpy.unique() Syntax Syntax: numpy.unique(arr, return_counts=False) Return: Sorted unique elements of an array with their corresponding f
4 min read
NumPy ndarray.__eq__() Method | Compare Array Values to Specific Value
The ndarray.__eq__() method of Numpy compares the values in ndarray to a specific value. It is useful to find which value in ndarray is equal to the given value. It will return you a NumPy array with a boolean type having only values True and False. Example C/C++ Code # import the important module in python import numpy as np # make an array with n
2 min read
NumPy | Get the Powers of Array Values Element-Wise
To calculate the power of elements in an array we use the numpy.power() method of NumPy library. It raises the values of the first array to the powers in the second array. Example: C/C++ Code import numpy as np # creating the array sample_array1 = np.arange(5) sample_array2 = np.arange(0, 10, 2) print("Original array ") print("array1
3 min read
How to Remove rows in Numpy array that contains non-numeric values?
Many times NumPy arrays may contain NaN values that need to be removed to ensure the array is free from unnecessary or invalid data. This can be achieved using the np.isnan() function along with the Bitwise NOT operator. Note that this approach specifically targets NaN values and may not handle other non-numeric characters like strings. Example 1:
2 min read
Python | Numpy numpy.transpose()
With the help of Numpy numpy.transpose(), We can perform the simple function of transpose within one line by using numpy.transpose() method of Numpy. It can transpose the 2-D arrays on the other hand it has no effect on 1-D arrays. This method transpose the 2-D numpy array. Parameters: axes : [None, tuple of ints, or n ints] If anyone wants to pass
2 min read
Python | Numpy numpy.ndarray.__lt__()
With the help of numpy.ndarray.__lt__() method of Numpy, We can find that which element in an array is less than the value which is provided in the parameter. It will return you numpy array with boolean type having only values True and False. Syntax: ndarray.__lt__($self, value, /) Return: self<value Example #1 : In this example we can see that
1 min read
Python | Numpy numpy.ndarray.__gt__()
With the help of numpy.ndarray.__gt__() method of Numpy, We can find that which element in an array is greater then the value which is provided in the parameter. It will return you numpy array with boolean type having only values True and False. Syntax: ndarray.__gt__($self, value, /) Return: self>value Example #1 : In this example we can see th
1 min read
Python | Numpy numpy.ndarray.__le__()
With the help of numpy.ndarray.__le__() method of Numpy, We can find that which element in an array is less than or equal to the value which is provided in the parameter. It will return you numpy array with boolean type having only values True and False. Syntax: ndarray.__le__($self, value, /) Return: self<=value Example #1 : In this example we
1 min read
Python | Numpy numpy.ndarray.__ge__()
With the help of numpy.ndarray.__ge__() method of Numpy, We can find that which element in an array is greater then or equal to the value which is provided in the parameter. It will return you numpy array with boolean type having only values True and False. Syntax: ndarray.__ge__($self, value, /) Return: self>=value Example #1 : In this example
1 min read
Python | Numpy numpy.ndarray.__ne__()
With the help of numpy.ndarray.__ne__() method of Numpy, We can find that which element in an array is not equal to the value which is provided in the parameter. It will return you numpy array with boolean type having only values True and False. Syntax: ndarray.__ne__($self, value, /) Return: self!=value Example #1 : In this example we can see that
1 min read
Practice Tags :
three90RightbarBannerImg