w3resource

NumPy: Sort a given array of shape 2 along the first axis, last axis and on flattened array

NumPy Sorting and Searching: Exercise-1 with Solution

Write a NumPy program to sort a given array of shape 2 along the first axis, last axis and on flattened array.

Sample Solution:

Python Code:

# Importing NumPy library and aliasing it as np
import numpy as np

# Creating a 2x2 NumPy array 'a'
a = np.array([[10, 40], [30, 20]])

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

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

# Sorting the array 'a' along the last axis (axis=-1, default behavior)
print("Sort the array along the last axis:")
print(np.sort(a))

# Sorting the flattened array 'a'
print("Sort the flattened array:")
print(np.sort(a, axis=None)) 

Sample Output:

Original array:
[[10 40]
 [30 20]]
Sort the array along the first axis:
[[10 20]
 [30 40]]
Sort the array along the last axis:
[[10 40]
 [20 30]]
Sort the flattened array:
[10 20 30 40]

Explanation:

In the above code –

a = np.array([[10, 40], [30, 20]]): This line creates a 2D array a with shape (2, 2) and the following elements:

print(np.sort(a, axis=0)): This line sorts the array a along the vertical axis (axis=0) and prints the result.

print(np.sort(a)): This line sorts the array a along the last axis (by default, axis=-1) and prints the result. In this case, it sorts each row of the array individually.

print(np.sort(a, axis=None)): This line flattens the array a, sorts the elements, and prints the result.

Pictorial Presentation:

NumPy: Sort a given array of shape 2 along the first axis, last axis and on flattened array.

Python-Numpy Code Editor:

Previous:NumPy Sorting and Searching Exercises Home.
Next: Write a NumPy program to create a structured array from given student name, height, class and their data types. Now sort the array on height.

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.