w3resource

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.

To sort each column of a 5x5 array with random values in NumPy, you can generate the array using numpy.random.rand. Then, use the numpy.sort function with the axis parameter set to 0, which sorts the elements within each column independently. This results in a 5x5 array where each column is sorted in ascending order.

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)

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.



Follow us on Facebook and Twitter for latest update.