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 first name and last name 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:

import numpy as np
first_names =    ('Margery', 'Betsey', 'Shelley', 'Lanell', 'Genesis')
last_names = ('Woolum', 'Battle', 'Plotner', 'Brien', 'Stahl')
x = np.lexsort((first_names, last_names))
print(x)

Sample Output:

[1 3 2 4 0] 

Python Code Editor:

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

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 Python skills with w3resource's quiz



Python: Tips of the Day

List comprehension:

>>> m = [x ** 2 for x in range(5)]
>>> m
[0, 1, 4, 9, 16]