w3resource

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

NumPy: Array Object Exercise-30 with Solution

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:

Previous: Write a NumPy program to sort an along the first, last axis of an array.
Next: Write a NumPy program to get the values and indices of the elements that are bigger than 10 in a given array.

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.