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 of a given numpy array.

Sample Solution:

Python Code:

import numpy as np
array1 = np.array([1, 7, 8, 2, 0.1, 3, 15, 2.5])
print("Original arrays:")
print(array1)
k = 4
result = np.argpartition(array1, k)
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]

Pictorial Presentation:

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

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

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 Python skills with w3resource's quiz



Python: Tips of the Day

List comprehension:

>>> m = [x ** 2 for x in range(5)]
>>> m
[0, 1, 4, 9, 16]