w3resource

NumPy: Sort an given array by the nth column


9. Sort Array by Nth Column

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.

For more Practice: Solve these Related Problems:

  • Sort a 2D array by the values in its nth column using np.argsort and advanced indexing to reorder rows.
  • Create a function that takes a 2D array and a column index as input, then returns the array sorted by that column.
  • Implement a solution that first extracts the nth column, sorts it, and uses the sorted indices to rearrange the entire array.
  • Test the sorting function on arrays with multiple columns to verify that sorting by the nth column produces the expected ordering.

Go to:


PREV : Partial Sorting from the Beginning of an Array.
NEXT : NumPy Advanced Indexing Exercises Home.

Python-Numpy Code Editor:

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

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.