w3resource

NumPy: Sort an given array by the nth column

NumPy Sorting and Searching: Exercise-9 with Solution

Write a NumPy program to sort an given array by the nth column.

Sample Solution:

Python Code:

# Importing the NumPy library
import numpy as np

# Displaying a message indicating the original array is going to be printed
print("Original array:\n")

# Generating a 3x3 array of random integers from 0 to 10
nums = np.random.randint(0, 10, (3, 3))

# Displaying the original array
print(nums)

# Displaying a message indicating sorting the array by the nth column
print("\nSort the said array by the nth column: ")

# Sorting the array by the values in the nth column using argsort
print(nums[nums[:, 1].argsort()]) 

Sample Output:

Original array:

[[1 5 0]
 [3 2 5]
 [8 7 6]]

Sort the said array by the nth column: 
[[3 2 5]
 [1 5 0]
 [8 7 6]]

Explanation:

In the above exercise –

nums = np.random.randint(0, 10, (3, 3)): This line creates a 3x3 NumPy array nums containing random integers from 0 (inclusive) to 10 (exclusive).

nums[:, 1]: This line slices the array nums to select all rows and the second column (index 1). The result is a 1D array containing the second column's elements.

nums[:, 1].argsort(): This line uses the argsort() function to obtain the indices that would sort the 1D array containing the elements of the second column.

print(nums[nums[:, 1].argsort()]): This line prints the result of indexing the original nums array using the sorted indices obtained in the previous step. This results in a new array where rows are sorted based on the values in the second column.

Python-Numpy Code Editor:

Previous: Write a NumPy program to sort the specified number of elements from beginning of a given array.
Next: Sorting and Searching Exercises Home.

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.