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 in a given array.

Sample Solution:

Python Code:

# Importing the NumPy library and aliasing it as 'np'
import numpy as np

# Creating a NumPy array 'array' containing integers
array = np.array([24, 27, 30, 29, 18, 14])

# Displaying a message indicating the original array will be printed
print("Original array:")

# Printing the original array
print(array)

# Getting the indices that would sort the 'array' in ascending order
argsort_array = array.argsort()

# Creating an empty array 'ranks_array' with the same shape as 'argsort_array'
ranks_array = np.empty_like(argsort_array)

# Assigning ranks to elements based on their sorted indices
ranks_array[argsort_array] = np.arange(len(array))

# Displaying a message indicating the ranks of each item in the array
print("\nRank of each item of the said array:")

# Printing the ranks of each item in the '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]

Explanation:

In the above exercise -

array = numpy.array([24, 27, 30, 29, 18, 14]): It creates a 1-dimensional NumPy array array with the given elements.

argsort_array = array.argsort(): It applies the argsort() function to the array, which returns the indices that would sort the array in ascending order.

ranks_array = numpy.empty_like(argsort_array): It creates a new NumPy array ranks_array with the same shape as argsort_array and uninitialized elements.

ranks_array[argsort_array] = numpy.arange(len(array)): It assigns the rank (position) of each element in the sorted array to the corresponding index in ranks_array. The numpy.arange(len(array)) creates an array of indices [0, 1, 2, 3, 4, 5], which represents the ranks of the sorted elements

print(ranks_array): Finally print() function prints the ranks_array, which shows the rank of each element in the original array.

Pictorial Presentation:

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

Python-Numpy Code Editor:

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



Follow us on Facebook and Twitter for latest update.