w3resource logo

:

Python Exercises

Python NumPy: Sort an along the first, last axis of an array

Python NumPy: Array Object Exercise-29 with Solution

Write a Python program to sort an along the first, last axis of an array.
Sample array: [[2,5],[4,4]]

Sample Solution:-

Python Code:

import numpy as np
a = np.array([[4, 6],[2, 1]])
print("Original array: ")
print(a)
print("Sort along the first axis: ")
x = np.sort(a, axis=0)
print(x)
print("Sort along the last axis: ")
y = np.sort(x, axis=1)
print(y)

Sample Output:

Expected Output:
Original array:                                                                        
[[4 6]                                                                                 
 [2 1]]                                                                                
Sort along the first axis:                                                             
[[2 1]                                                                                 
 [4 6]]                                                                                
Sort along the last axis:                                                              
[[1 2]                                                                                 
 [4 6]] 

Python Code Editor:

Improve this sample solution and post your code through Disqus