Advanced NumPy Exercises - Create a 5x5 array with random values and sort each column
NumPy: Advanced Exercise-10 with Solution
Write a NumPy program to create a 5x5 array with random values and sort each column.
Sample Solution:
Python Code:
import numpy as np
# create a 5x5 array with random values
nums = np.random.rand(5, 5)
print("Original array elements:")
print(nums)
# sort each column
arr_sorted = np.sort(nums, axis=0)
# print the sorted array
print("\nSort each column of the said array:")
print(arr_sorted)
Sample Output:
Original array elements: [[0.47879982 0.93270918 0.31841905 0.67430192 0.59557056] [0.70619839 0.46692327 0.50879651 0.34982804 0.79226702] [0.32962844 0.1159612 0.79646603 0.3882432 0.20331094] [0.85085553 0.66209602 0.0451838 0.45887268 0.61541116] [0.9627565 0.94620249 0.54923636 0.81244472 0.08528689]] Sort each column of the said array: [[0.32962844 0.1159612 0.0451838 0.34982804 0.08528689] [0.47879982 0.46692327 0.31841905 0.3882432 0.20331094] [0.70619839 0.66209602 0.50879651 0.45887268 0.59557056] [0.85085553 0.93270918 0.54923636 0.67430192 0.61541116] [0.9627565 0.94620249 0.79646603 0.81244472 0.79226702]]
Explanation:
In the above exercise -
nums = np.random.rand(5, 5): Creates a 5x5 array of random numbers between 0 and 1 using the rand function from the numpy.random module.
arr_sorted = np.sort(nums, axis=0): Sorts the array nums along the first axis (columns) using the sort function from numpy. This means that each column will be sorted in ascending order, but the order of the rows within each column will not change.
Python-Numpy Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Create a 5x5 array with random values and sort each row.
Next: Find the second-largest value in each row in an array .
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Python: Tips of the Day
Summing a sequence of numbers (calculating the sum of zero to ten with skips):
>>> l = range(0,10,2) >>> sum(l) 20
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook