w3resource

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


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: