w3resource

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

NumPy: Array Object Exercise-29 with Solution

Sort Array Along Axes

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

Sample Solution:

Python Code:

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

# Creating a NumPy array 'a'
a = np.array([[4, 6], [2, 1]])

# Displaying the original array 'a'
print("Original array: ")
print(a)

# Sorting along the first axis (axis 0)
print("Sort along the first axis: ")
x = np.sort(a, axis=0)
print(x)

# Sorting along the last axis (axis 1) of the previously sorted array '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]] 

Explanation:

In the above code -

a = np.array([[4, 6],[2, 1]]): A 2D NumPy array a is created with the shape (2, 2) and the elements are [[4, 6], [2, 1]].

x = np.sort(a, axis=0): The np.sort function sorts the input array a along the specified axis, which is 0 (columns) in this case. The result is stored in the variable ‘x’, which is an array with the same shape as a, but with the elements sorted along each column. The resulting array ‘x’ is [[2, 1], [4, 6]].

y = np.sort(x, axis=1): The np.sort function is called again, this time with the input array ‘x ‘ and the specified axis set to 1 (rows). The function sorts the elements along each row, and the result is stored in the variable ‘y’. The resulting array y is [[1, 2], [4, 6]].

Python-Numpy Code Editor:

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 Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-exercises/numpy/python-numpy-exercise-29.php