trimmed_weighted_mean#
- bamengine.utils.trimmed_weighted_mean(values, weights=None, trim_pct=0.05, min_weight=0.001)[source]#
Calculate trimmed weighted mean with optional weight filtering.
Computes a weighted mean after (1) filtering out entries with negligible weights, and (2) trimming extreme values. If no weights are provided, falls back to unweighted trimmed mean.
- Parameters:
values (
Float1D) – 1D array of values to average.weights (
Float1D, optional) – 1D array of weights (same length as values). If None, computes unweighted trimmed mean (ignores min_weight parameter).trim_pct (
float, optional) – Proportion of values to trim from each tail (default: 0.05 = 5%). Trimming is applied after weight filtering.min_weight (
float, optional) – Minimum weight threshold (default: 1e-3). Entries with weights below this are excluded before computing mean. Ignored if weights is None.
- Returns:
Trimmed weighted mean. Returns 0.0 if no valid entries remain after filtering and trimming.
- Return type:
Examples
Weighted mean with weight filtering:
>>> import numpy as np >>> from bamengine.utils import trimmed_weighted_mean >>> values = np.array([10, 20, 30, 40]) >>> weights = np.array([0.5, 1.0, 1.5, 0.0001]) # Last weight too small >>> trimmed_weighted_mean(values, weights, trim_pct=0.0, min_weight=0.01) 22.0 # Only first 3 values included
Trimmed weighted mean:
>>> values = np.array([1, 2, 3, 100]) # 100 is outlier >>> weights = np.array([1, 1, 1, 1]) >>> trimmed_weighted_mean(values, weights, trim_pct=0.25) # Trims 1 from each end 2.5 # Mean of [2, 3]
Unweighted mode (weights=None):
>>> values = np.array([1, 2, 3, 4, 5]) >>> trimmed_weighted_mean(values, weights=None, trim_pct=0.20) 3.0 # Regular trimmed mean
Notes
Weight filtering occurs before trimming
Trimming is based on value ordering (not weight ordering)
Falls back to unweighted mean if all weights are zero
If weights is None, min_weight parameter is ignored
See also
trim_meanUnweighted trimmed mean (faster if no weights needed)
numpy.averageNumPy weighted average (no trimming)