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:
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
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.
- New Content published on w3resource:
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- React - JavaScript Library
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework