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:

# Importing the NumPy library
import numpy as np

# Creating an array of 10 random numbers
nums = np.random.rand(10)

# Displaying the original array
print("Original array:")
print(nums)

# Sorting the first 5 elements using argpartition
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]

Explanation:

nums = np.random.rand(10): This line creates a NumPy array nums containing 10 random float elements from a uniform distribution over [0, 1).

np.argpartition(nums, range(5)): This line uses the np.argpartition function to partition the indices of the array nums at the specified index positions, which in this case is a range from 0 to 4. The result is a new array of indices where the elements before the specified indices (0 to 4) are indices of smaller elements, and the elements after the indices are indices of larger elements. The order of the indices within each partition is not guaranteed to be sorted.

print(nums[np.argpartition(nums, range(5))]): This line prints the result of indexing the original nums array using the partitioned indices, which returns the smallest 5 elements from the original nums array.

Pictorial Presentation:

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

Python-Numpy Code Editor:

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

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://www.w3resource.com/python-exercises/numpy/python-numpy-sorting-and-searching-exercise-8.php