Percentiles and Spread
Percentile Rank
A percentile rank answers: what percentage of the data falls at or below a
given value? Definition used here: rank = (count of values ≤ target) / n ×
100 — the "weak" definition. Loop over values, count those ≤ target, divide
by n and scale to 100. With scipy, percentileofscore(x, target, kind='weak') uses the same ≤ rule. Values: [2,4,...,20] n=10, target=12 →
6 values ≤ 12 → rank=60.0.
By hand
With the library
scipy.stats.percentileofscore(x, target, kind='weak') counts values ≤
target and scales to 100 — identical to the naive formula. kind='strict'
counts strictly < target; kind='mean' averages the two. Always specify
kind explicitly to avoid ambiguity.
naive.py
values = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
target = 12
n = len(values)
count = 0
for v in values:
if v <= target:
count = count + 1
rank = count / n * 100
print('RESULT:', round(rank, 2))
library.py
from scipy.stats import percentileofscore
from dalib.display import set_display
set_display()
values = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
target = 12
rank = percentileofscore(values, target, kind='weak')
print('target:', target)
print('n:', len(values))
print('RESULT:', round(rank, 2))
target: 12
n: 10
RESULT: 60.0
Implementation notes
kind='weak'(≤) is the most common definition and matches the intuition "12 is at the 60th percentile."kind='strict'(<) gives 50.0 here (five values below 12);kind='mean'gives 55.0.- Percentile rank is the inverse of
np.percentile: given a rank, percentile gives the value; given a value, percentile rank gives the rank. - Cross-reference:
five-number-summary(this chapter) for the fixed landmarks (0, 25, 50, 75, 100th percentiles) of a distribution.