Unlike the mean, the median isn't affected by extreme outliers, since it only depends on the position of values once sorted, not their actual magnitude — a small dataset with one huge outlier has a mean dragged way up by that outlier, but a median that still reflects the typical value much better. Computing it requires sorting, or an equivalent selection algorithm, internally, which is more expensive than computing a mean, but that's rarely a practical concern for typical dataset sizes.
1Understanding np.median()
Unlike the mean, the median isn't affected by extreme outliers, since it only depends on the position of values once sorted, not their actual magnitude — a small dataset with one huge outlier has a mean dragged way up by that outlier, but a median that still reflects the typical value much better. Computing it requires sorting, or an equivalent selection algorithm, internally, which is more expensive than computing a mean, but that's rarely a practical concern for typical dataset sizes.
Prefer the median over the mean specifically when a dataset likely contains outliers or a skewed distribution, like income or response-time data, since the mean can be pulled far away from the typical value by a small number of extreme points.
import numpy as np
arr = np.array([1, 3, 3, 6, 7, 8, 9])
print(np.median(arr))2Practical Example
Here is a real-world application of np.median() showing how it is used in production NumPy code.
import numpy as np
incomes = np.array([30000, 32000, 31000, 500000])
print(np.mean(incomes))
print(np.median(incomes))3Best Practices
Follow these guidelines when working with np.median():
1. Use the median instead of the mean when outliers or skew could distort what 'typical' means for the dataset
2. Use np.nanmedian() when the data might contain NaN values that should be ignored
3. Check whether an even-length dataset's median, an average of two middle values, actually appears as a real data point or just falls between two, if that distinction matters for your use case
Tip: Prefer the median over the mean specifically when a dataset likely contains outliers or a skewed distribution, like income or response-time data, since the mean can be pulled far away from the typical value by a small number of extreme points.
import numpy as np
arr = np.array([1, 3, 3, 6, 7, 8, 9])
print(np.median(arr))