w3resource

Advanced NumPy Exercises - Create a 5x5 array with random values and sort each row

NumPy: Advanced Exercise-9 with Solution

Write a NumPy program to create a 5x5 array with random values and sort each row.

In NumPy, you can create a 5x5 array with random values using numpy.random.rand. To sort each row of this array, use the numpy.sort function along the appropriate axis. By setting the axis parameter to 1, the function will sort the elements within each row independently, resulting in a 5x5 array where each row 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 row
sorted_arr = np.sort(nums, axis=1)
print("\nSort each row of the said array:")
print(sorted_arr)

Output:

Original array elements:
[[0.80639523 0.85676788 0.63735358 0.19722163 0.30498022]
 [0.28281787 0.79034684 0.75880613 0.48208842 0.08480249]
 [0.81731506 0.5283993  0.96713901 0.92397872 0.66484352]
 [0.97135896 0.63695905 0.16203036 0.38395203 0.93927903]
 [0.04436282 0.94906948 0.07663907 0.98783301 0.4181465 ]]

Sort each row of the said array:
[[0.19722163 0.30498022 0.63735358 0.80639523 0.85676788]
 [0.08480249 0.28281787 0.48208842 0.75880613 0.79034684]
 [0.5283993  0.66484352 0.81731506 0.92397872 0.96713901]
 [0.16203036 0.38395203 0.63695905 0.93927903 0.97135896]
 [0.04436282 0.07663907 0.4181465  0.94906948 0.98783301]]

Explanation:

In the above exercise -

nums = np.random.rand(5, 5): Create a 5x5 array of random values between 0 and 1.

sorted_arr = np.sort(nums, axis=1): Sort the elements of nums along the second axis (i.e., sort each row in ascending order) and assign the sorted array to sorted_arr.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Find the sum along the last axis of a 3x3x3 array.
Next: Create a 5x5 array with random values and sort each column.

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.