torch.Tensor.Tensor.nanmedian
Computes the median value, ignoring NaN elements.
Returns the middle value (for odd-length) or average of two middle values (for even-length) after removing NaN values. Essential for:
- Robust statistics: Median is unaffected by outliers or NaN values
- Data cleaning: Computing statistics despite missing data (NaN)
- Quality metrics: Using median instead of mean for outlier-resistant metrics
- Data preprocessing: Handling datasets with missing values
- Tensor-wide reduction: Finding central tendency of entire tensor
Returns a scalar tensor with the median value. NaN values are completely ignored, and the median is computed over remaining elements. If all values are NaN, returns NaN.
- Ignores all dimensions: nanmedian operates on the entire tensor, not per-dimension. For per-dimension median, use median() with manual NaN handling.
- Returns scalar: Result is always a scalar tensor (0D), regardless of input shape.
- Odd vs even: For odd number of elements, returns middle value directly. For even, returns average of two middle values.
- NaN propagation: If all elements are NaN, result is NaN. If some are NaN, they're simply ignored.
- Outlier robust: Median is not affected by extreme outliers, making it more robust than mean for noisy data.
- All NaN input: Returns NaN if every element is NaN. Check for this case if needed.
- No per-dimension option: This function always reduces to a scalar. For per-dimension reductions, use median() and handle NaN separately.
Returns
Tensor<readonly [], D, Dev>– Scalar tensor containing the median value (NaN values ignored)Examples
// Median of tensor with NaN values
const x = torch.tensor([1, 2, NaN, 4, 5]);
const med = x.nanmedian(); // 3.0 (ignores NaN, median of [1,2,4,5])// Robust average for data with outliers/NaN
const sensor_data = torch.tensor([98.5, 98.6, 104.2, NaN, 98.7, 98.4]);
const robust_center = sensor_data.nanmedian();
// Better than mean due to outlier and missing value// Even-length gives average of middle two
const even_data = torch.tensor([10, 20, NaN, 30, 40, NaN]);
const med = even_data.nanmedian(); // (20 + 30) / 2 = 25// Tensor-wide reduction
const matrix = torch.tensor([[1, NaN, 3], [4, 5, NaN]]);
const med = matrix.nanmedian(); // median of [1,3,4,5] = 3.5// All NaN returns NaN
const all_nan = torch.tensor([NaN, NaN, NaN]);
const result = all_nan.nanmedian(); // NaNSee Also
- PyTorch tensor.nanmedian()
- median - Median without NaN handling
- nanmean - Mean ignoring NaN values
- nansum - Sum ignoring NaN values