Robust central tendency
Summarize skewed measurements
NumPy · Function
Computes the median of array elements along selected axes. It averages the two central values for even-sized data and can preserve reduced dimensions for broadcasting.
np.median computes the middle value of array data after ordering it along the requested axis. With an odd number of values it selects the central value; with an even number it averages the two central values, and it can preserve reduced axes for shape-compatible operations.
numpy.median(a, axis=None, out=None, overwrite_input=False, keepdims=False)| Name | Type | Description |
|---|---|---|
a | array_like | Input array or object that can be converted to an array. |
axis | int, sequence of int, None | Axis or axes along which the medians are computed; None flattens the input first. |
out | ndarray, optional | Array in which to place the result; it must have the appropriate shape. |
overwrite_input | bool, optional | If True, allow the computation to modify the input array for memory efficiency. |
keepdims | bool, optional | If True, leave reduced axes in the result with length one. |
An ndarray containing the median result; if out is supplied, that array is returned instead.
import numpy as np
values = np.array([[1, 9, 3], [8, 2, 7]])
print(np.median(values))
print(np.median(values, axis=0))
print(np.median(values, axis=1, keepdims=True))Computes the overall median, column medians, and row medians while retaining the reduced axis for broadcasting.
Summarize skewed measurements
Reduce rows or columns
Normalize with shape-compatible statistics
Reuse allocated result storage
np.median returns the median of array elements along the selected axis. For an odd-length sequence it uses the middle sorted value; for an even-length sequence it averages the two middle sorted values.
Follow-up: How does axis=None differ from axis=0? axis=None flattens the array first, whereas axis=0 reduces the first dimension independently across the remaining dimensions.
The axis argument selects one axis, multiple axes, or all axes with None. A sequence of axes is flattened together before the median is computed.
Follow-up: When would keepdims=True help? It preserves reduced axes with length one, which makes the result easier to broadcast against the original array.
For integer or lower-precision floating input, the result uses np.float64. Otherwise, the result keeps the input data type; specifying out places and returns the result in the supplied array.
Follow-up: What trade-off does overwrite_input=True provide? It may reduce temporary memory use by reusing the input, but it can alter that input array.
numpy.meannumpy.percentile