mutcleaner.utils.label_resolvers#
Label resolvers for aggregating per-group target columns.
This module provides small, composable resolvers—callables that, given a
pandas DataFrame group and a list of label columns, return a
Series of resolved label values. Resolvers are intended to be used inside
grouped operations (e.g., DataFrameGroupBy.apply) where multiple rows per
entity must be collapsed to a single, consistent set of labels.
The public entry point make_resolver() constructs a resolver from a
strategy name (e.g., "mean", "first", "nearest") or accepts a
user-supplied callable. The nearest_resolver_factory() enables
lexicographic, weighted “nearest row” selection across multiple numeric
criteria columns.
Notes#
Resolver signature:
Resolver = Callable[[pd.DataFrame, list[str]], pd.Series]. The returnedSeriesmust align with the providedlabel_colsorder.Missing values: For the
"nearest"strategy, missing (NaN) values in criterion columns are treated as+infdistance so such rows never win.Column order: When using mappings (
dict) for criteria, Python 3.7+ preserves insertion order. That order determines lexicographic priority.Type expectations: -
"mean"requires numeric label columns; non-numeric values raiseValueError."nearest"requires numeric criterion columns; non-numeric values raiseValueError.
Error handling: Missing required columns raise
KeyError; unknown strategy names raiseValueError.
See Also#
pandas.DataFrame.groupby : Grouping rows for split-apply-combine workflows. numpy.lexsort : Related concept for lexicographic ordering.
Functions
|
Create or return a label resolver from a strategy name or callable. |
- mutcleaner.utils.label_resolvers.make_resolver(strategy, *, nearest_by=None, nearest_weights=None)[source]#
Create or return a label resolver from a strategy name or callable.
- Parameters:
strategy (
Union[str,Callable[[DataFrame,List[str]],Series]]) – Strategy identifier or a custom resolver. If a callable is provided, it must have signature(group: DataFrame, label_cols: list[str]) -> Series.nearest_by (
Union[Mapping[str,float],Sequence[Tuple[str,float]],None]) – Criteria for the"nearest"strategy. Required whenstrategy="nearest". Seenearest_resolver_factory().nearest_weights (
Union[Mapping[str,float],Sequence[Tuple[str,float]],None]) – Weights for the"nearest"strategy. Seenearest_resolver_factory().
- Return type:
Callable[[DataFrame,List[str]],Series]- Returns:
A resolver callable that can be passed into higher-level aggregation code.
- Raises:
ValueError – If
strategyis unknown or required parameters are missing for the"nearest"strategy.
Examples
>>> res = make_resolver("mean") >>> # or nearest: >>> res = make_resolver("nearest", nearest_by={"temperature": 25.0}) >>> # or custom: >>> def pick_row(g, labels): ... return g.loc[g["score"].idxmax(), labels] >>> res = make_resolver(pick_row)