w3resource

NumPy: Sort pairs of first name and last name return their indices


Sort Pairs by Names

Write a NumPy program to sort pairs of a first name and a last name and return their indices (first by last name, then by first name).
first_names = (‘Betsey’, ‘Shelley’, ‘Lanell’, ‘Genesis’, ‘Margery’)
last_names = (‘Battle’, ‘Brien’, ‘Plotner’, ‘Stahl’, ‘Woolum’)

Sample Solution:

Python Code:

# Importing the NumPy library with an alias 'np'
import numpy as np

# Tuple of first names
first_names = ('Margery', 'Betsey', 'Shelley', 'Lanell', 'Genesis')

# Tuple of last names
last_names = ('Woolum', 'Battle', 'Plotner', 'Brien', 'Stahl')

# Lexicographically sorts the tuples of names and returns an array of indices that sorts them
x = np.lexsort((first_names, last_names))

# Displaying the resulting indices that would sort the tuples lexicographically
print(x)

Sample Output:

[1 3 2 4 0] 

Explanation:

The above code demonstrates how to sort two arrays lexicographically using the np.lexsort function.

‘first_names’ and ‘last_names’ are tuples containing names.

x = np.lexsort((first_names, last_names)): The np.lexsort function is called with a tuple containing the two arrays ‘first_names’ and ‘last_names’. The function sorts the data lexicographically based on the last array passed (in this case, ‘last_names’), then breaks ties using the previous arrays (in this case, ‘first_names’). The result is an array of indices that would sort the data lexicographically. The resulting array x is [1, 3, 2, 4, 0].


For more Practice: Solve these Related Problems:

  • Given two arrays of first and last names, sort them primarily by last name and then by first name using lexsort.
  • Create a structured array from the names and use np.argsort to determine the correct order.
  • Return the sorted indices and reconstruct the full names to verify the order.
  • Handle duplicate last names by sorting the associated first names correctly and verifying the final sequence.

Go to:


PREV : Sort Array Along Axes
NEXT : Elements >10 & Their Indices


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.