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

NumPy: Array Object Exercise-29 with Solution

Write a NumPy 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("Sort along the first axis: ")
x = np.sort(a, axis=0)
print("Sort along the last axis: ")
y = np.sort(x, axis=1)

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:

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

Previous: Write a NumPy program compare two arrays using numpy.
Next: Write a NumPy program to sort pairs of first name and last name return their indices. (first by last name, then by first name).

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz

Python: Tips of the Day

Set comprehension:

>>> m = {x ** 2 for x in range(5)}
>>> m
{0, 1, 4, 9, 16}