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:

import numpy as np
a = np.array([[10,40],[30,20]])
print("Original array:")
print(a)
print("Sort the array along the first axis:")
print(np.sort(a, axis=0))
print("Sort the array along the last axis:")
print(np.sort(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]

Pictorial Presentation:

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

Python Code Editor:

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

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



Python: Tips of the Day

Python: Find the number of occurrence of each values in an iterable

It returns True only if two values point to same object.