w3resource

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


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: