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].

Python-Numpy Code Editor: