w3resource

NumPy: Create an array that represents the rank of each item of a given array

NumPy: Array Object Exercise-147 with Solution

Write a NumPy program to create an array that represents the rank of each item of a given array.

Sample Solution:

Python Code:

import numpy as numpy
array = numpy.array([24, 27, 30, 29, 18, 14])
print("Original array:")
print(array)
argsort_array = array.argsort()
ranks_array = numpy.empty_like(argsort_array)
ranks_array[argsort_array] = numpy.arange(len(array))
print("\nRank of each item of the said array:")
print(ranks_array)

Sample Output:

Original array:
[24 27 30 29 18 14]

Rank of each item of the said array:
[2 3 5 4 1 0]

Pictorial Presentation:

NumPy: Create an array that represents the rank of each item of a given array

Python Code Editor:

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

Previous: Write a NumPy program to add two arrays A and B of sizes (3,3) and (,3).
Next: Write a NumPy program to copy data from a given array to another array.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Set comprehension:

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