get the k smallest values from a numpy array

Get the k smallest values in a Numpy Array

The Numpy library in Python comes with a number of useful functions and techniques to work with and manipulate the data in arrays. In this tutorial, we will look at how to get the k smallest values from a one-dimensional Numpy array (where k <= size of the array).

How to get the k smallest values from a Numpy array?

get the k smallest values from a numpy array

To get the k smallest values from a Numpy array, first, sort the array (in ascending order) and then slice the first k values of the sorted array.

The following is the syntax –

# k smallest elements from numpy array ar
np.sort(ar)[:k]

Here, the np.sort() function returns a sorted copy of the array, we then slice this sorted array to get the first k values (which are the k smallest values since the array is sorted in ascending order).

Steps to get the k smallest elements in a Numpy array

Let’s now look at a step-by-step example of using the above method. Here, we will create a numeric array of size 7 and get the 3 smallest elements in the array. That is k = 3.

Step 1 – Create a Numpy array

First, we will create a Numpy array that we will be using throughout this tutorial.

import numpy as np

# create numpy array
ar = [3, 1, 5, 7, 4, 2, 6]
# display the array
print(ar)

Output:

[3, 1, 5, 7, 4, 2, 6]

Here, we used the numpy.array() function to create a one-dimensional Numpy array of length 7 containing numeric values.

📚 Data Science Programs By Skill Level

Introductory

Intermediate ⭐⭐⭐

Advanced ⭐⭐⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

Step 2 – Sort the array

Now, we will use the numpy.sort() function to sort the array created above. This function returns a sorted copy of the original array and doesn’t modify it in-place.

# sort the array
sorted_ar = np.sort(ar)
# display the array
print(sorted_ar)

Output:

[1 2 3 4 5 6 7]

The resulting array is sorted in ascending order.

Note – To sort a Numpy array, you can also use the instance method numpy.ndarray.sort() (for example, ar.sort()). This function sorts the array in-place.

Step 3 – Slice the sorted array to get the k smallest elements

As the array is sorted in ascending order, the first k elements of the array are the k smallest elements in the array.

Slice the sorted array to get the first k elements (slice from the start of the array to k).

For example, let’s get the 3 smallest elements in the array (k=3).

# get the 3 smallest elements
print(sorted_ar[:3])

Output:

[1 2 3]

We get the 3 smallest elements in the array.

You can combine the code for the last two steps in a single line and avoid the extra variable.

# get the 3 smallest elements
print(np.sort(ar)[:3])

Output:

[1 2 3]

We get the same result as above.

Summary – Get k smallest elements from a Numpy array

In this tutorial, we looked at how to get the k smallest elements from a Numpy array. The following is a short summary of the steps mentioned in this tutorial.

  1. Create a Numpy array (skip this step if you already have an array to operate on).
  2. Sort the Numpy array using the numpy.sort() function.
  3. To get the k smallest elements in the array –
    • Slice the first k elements of the sorted array if you sorted the array in ascending order.
    • Slice the last k elements of the sorted array if you sorted the array in descending order.

You might also be interested in –


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.


Author

  • Piyush Raj profile picture

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

    View all posts
Scroll to Top