w3resource

NumPy: Sort a given array by row and column in ascending order

NumPy: Basic Exercise-52 with Solution

Write a NumPy program to sort a given array by row and column in ascending order.

Sample Solution:

Python Code :

# Importing the NumPy library with an alias 'np'
import numpy as np  

# Creating a NumPy array 'nums' containing values in a 3x3 matrix
nums = np.array([[5.54, 3.38, 7.99],
              [3.54, 4.38, 6.99],
              [1.54, 2.39, 9.29]])

# Printing a message indicating the original array
print("Original array:")
print(nums)

# Sorting the array 'nums' by rows in ascending order and displaying the sorted result
print("\nSort the said array by row in ascending order:")
print(np.sort(nums))

# Sorting the array 'nums' by columns in ascending order and displaying the sorted result
print("\nSort the said array by column in ascending order:")
print(np.sort(nums, axis=0)) 

Sample Output:

Original array:
[[5.54 3.38 7.99]
 [3.54 4.38 6.99]
 [1.54 2.39 9.29]]

Sort the said array by row in ascending order:
[[3.38 5.54 7.99]
 [3.54 4.38 6.99]
 [1.54 2.39 9.29]]

Sort the said array by column in ascending order:
[[1.54 2.39 6.99]
 [3.54 3.38 7.99]
 [5.54 4.38 9.29]]

Explanation:

np.array(...): Creates a 3x3 NumPy array with the given values and stores in the variable ‘nums’

print(np.sort(nums)): This line sorts the nums array along the last axis (axis=-1 or axis=1) by default. Each row is sorted individually. The results are printed.

print(np.sort(nums, axis=0)): This line sorts the nums array along the first axis (axis=0). Each column is sorted individually. The results are printed.

Python-Numpy Code Editor:

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

Previous: NumPy program to create a new array of given shape (5,6) and type, filled with zeros.
Next: NumPy program to extract all numbers from a given array which are less and greater than a specified number.

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.