Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python - Index Ranks of Elements
When working with data structures, you might need to determine the index rank of elements. Index ranking assigns a numerical rank to each element based on its relative position when sorted, where smaller values get lower ranks. This tutorial shows how to calculate index ranks using a custom Python function.
What is Index Ranking?
Index ranking assigns ranks to elements based on their sorted order:
- Smallest element gets rank 1
- Second smallest gets rank 2, and so on
- For duplicate elements, the average rank is assigned
Implementation
Here's how to calculate index ranks using a custom function ?
def find_rank_elem(my_list):
my_result = [0 for x in range(len(my_list))]
for elem in range(len(my_list)):
r, s = 1, 1 # r = rank, s = count of equal elements
for j in range(len(my_list)):
if j != elem and my_list[j] < my_list[elem]:
r += 1 # Count elements smaller than current
if j != elem and my_list[j] == my_list[elem]:
s += 1 # Count equal elements
# Average rank for duplicates
my_result[elem] = r + (s - 1) / 2
return my_result
my_list = [1, 3, 5, 3, 1, 26, 99, 45, 67, 12]
print("The list is :")
print(my_list)
print("The resultant list is :")
print(find_rank_elem(my_list))
The list is : [1, 3, 5, 3, 1, 26, 99, 45, 67, 12] The resultant list is : [1.0, 3.0, 5.0, 3.0, 1.0, 7.0, 10.0, 8.0, 9.0, 6.0]
How It Works
The algorithm works by comparing each element with every other element:
- Initialize rank (r) to 1 for each element
- Count smaller elements - increment rank for each smaller element found
- Count equal elements (s) - track duplicates for average ranking
-
Calculate final rank using formula:
r + (s - 1) / 2
Step-by-Step Example
For the list [1, 3, 5, 3, 1], let's trace element 3 (index 1):
# For element 3 at index 1
my_list = [1, 3, 5, 3, 1]
element = 3
r = 1 # Initial rank
s = 1 # Count of equal elements (itself)
# Compare with other elements:
# Index 0: 1 < 3, so r = 2
# Index 2: 5 > 3, no change
# Index 3: 3 == 3, so s = 2
# Index 4: 1 < 3, so r = 3
final_rank = r + (s - 1) / 2
print(f"Final rank: {final_rank}") # 3 + (2-1)/2 = 3.5
Final rank: 3.5
Using Built-in Methods
You can also use SciPy's rankdata for the same result ?
from scipy.stats import rankdata
my_list = [1, 3, 5, 3, 1, 26, 99, 45, 67, 12]
ranks = rankdata(my_list, method='average')
print("Using SciPy:", ranks)
Conclusion
Index ranking assigns numerical ranks to elements based on their sorted order, with duplicates receiving average ranks. The custom function compares each element with all others to determine its rank position.
