NumPy: Sort a given array by row and column in ascending order
Sort Array by Rows & Columns
Write a NumPy program to sort a given array by row and column in ascending order.
This problem involves writing a NumPy program to sort a given array by both row and column in ascending order. The task requires utilizing NumPy's sorting functions, such as "numpy.sort", along appropriate axes to achieve row-wise and column-wise sorting. By applying sorting operations separately to rows and columns, the program efficiently arranges the elements of the array in ascending order along both dimensions, facilitating data organization and analysis.
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))
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:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics