np.percentile(arr, 50) is exactly equivalent to np.median(arr), since the 50th percentile is by definition the median. Values of q other than an exact data-matching position, like 25 for the first quartile, or 90 for a common outlier-detection cutoff, are computed by interpolating between the two nearest actual data points, using linear interpolation by default, which is why the result isn't always a value that literally appears in the original dataset.
1Understanding np.percentile()
np.percentile(arr, 50) is exactly equivalent to np.median(arr), since the 50th percentile is by definition the median. Values of q other than an exact data-matching position, like 25 for the first quartile, or 90 for a common outlier-detection cutoff, are computed by interpolating between the two nearest actual data points, using linear interpolation by default, which is why the result isn't always a value that literally appears in the original dataset.
np.percentile(arr, 50) and np.median(arr) always return the same result — reach for percentile() when you need an arbitrary cutoff, and median() when you specifically mean the 50th percentile, for clearer, more self-documenting code.
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(np.percentile(arr, 50))
print(np.percentile(arr, 90))2Practical Example
Here is a real-world application of np.percentile() showing how it is used in production NumPy code.
import numpy as np
response_times = np.array([120, 150, 130, 800, 140, 135, 145])
p95 = np.percentile(response_times, 95)
print(p95)3Best Practices
Follow these guidelines when working with np.percentile():
1. Use np.percentile() for arbitrary cutoffs, like the 90th or 95th percentile for outlier or SLA-style analysis, rather than manually sorting and indexing
2. Use np.median() instead of np.percentile(arr, 50) when that's specifically what you mean, for clearer, more self-documenting code
3. Pass a list of q values to get several percentiles in a single call instead of computing them separately
Tip: np.percentile(arr, 50) and np.median(arr) always return the same result — reach for percentile() when you need an arbitrary cutoff, and median() when you specifically mean the 50th percentile, for clearer, more self-documenting code.
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(np.percentile(arr, 50))
print(np.percentile(arr, 90))