w3resource

NumPy: Sort the specified number of elements from beginning of a given array

NumPy Sorting and Searching: Exercise-8 with Solution

Write a NumPy program to sort the specified number of elements from beginning of a given array.

Sample Solution:

Python Code:

import numpy as np
nums =  np.random.rand(10)
print("Original array:")
print(nums)
print("\nSorted first 5 elements:")
print(nums[np.argpartition(nums,range(5))])

Sample Output:

Original array:
[0.39536213 0.11779404 0.32612381 0.16327394 0.98837963 0.25510787
 0.01398678 0.15188239 0.12057667 0.67278699]

Sorted first 5 elements:
[0.01398678 0.11779404 0.12057667 0.15188239 0.16327394 0.25510787
 0.39536213 0.98837963 0.32612381 0.67278699]

Pictorial Presentation:

NumPy: Sort the specified number of elements from beginning of a given array.

Python Code Editor:

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

Previous: Write a NumPy program to sort a given complex array using the real part first, then the imaginary part.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Python: Find the number of occurrence of each values in an iterable

It returns True only if two values point to same object.