NumPy: Sort pairs of first name and last name return their indices
NumPy: Array Object Exercise-30 with Solution
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:
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/python-exercises/numpy/python-numpy-exercise-30.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics