w3resource

NumPy: Find the k smallest values of a given numpy array

NumPy: Array Object Exercise-160 with Solution

Write a NumPy program to find the k smallest values in an array.

Sample Solution:

Python Code:

# Importing the NumPy library and aliasing it as 'np'
import numpy as np

# Creating a NumPy array
array1 = np.array([1, 7, 8, 2, 0.1, 3, 15, 2.5])

# Displaying the original array
print("Original arrays:")
print(array1)

# Specifying the number of smallest elements to find
k = 4

# Finding indices that partition the array into k smallest elements on the left and the rest on the right
result = np.argpartition(array1, k)

# Displaying the k smallest values in the original array using the partitioned indices
print("\nk smallest values:")
print(array1[result[:k]])

Sample Output:

Original arrays:
[ 1.   7.   8.   2.   0.1  3.  15.   2.5]

k smallest values:
[0.1 1.  2.  2.5]

Explanation:

numpy.argpartition(a, kth, axis=-1, kind='introselect', order=None)[source]

Perform an indirect partition along the given axis using the algorithm specified by the kind keyword. It returns an array of indices of the same shape as a that index data along the given axis in partitioned order.

kthint or sequence of ints

Element index to partition by. The k-th element will be in its final sorted position and all smaller elements will be moved before it and all larger elements behind it. The order of all elements in the partitions is undefined. If provided with a sequence of k-th it will partition all of them into their sorted position at once.

In the above exercise –

  • array1: This line creates a 1D NumPy array with the given values.
  • k: Declare the number of smallest elements to find.
  • result = np.argpartition(array1, k): It rearranges the array of the first k elements (Stated above the parameter ‘kth’ of argpartition() function.) and stores in the variable ‘result’.
  • array1[result[:k]]: Extract the first k elements of the rearranged array1, which are the k smallest elements.
  • Finally print() function prints the k smallest elements of the original array.

Pictorial Presentation:

NumPy: Find the k smallest values of a given numpy array

Python-Numpy Code Editor:

Previous: Write a NumPy program to rearrange columns of a given numpy 2D array using given index positions.
Next: Write a NumPy program to create a white image of size 512x256.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/numpy/python-numpy-exercise-160.php