diff --git a/microdf/microdataframe.py b/microdf/microdataframe.py index 32be4a0..2d6d332 100644 --- a/microdf/microdataframe.py +++ b/microdf/microdataframe.py @@ -10,6 +10,7 @@ from microdf.microseries import ( MicroSeries, MicroSeriesGroupBy, + _grouped_result_as_columns, _pair_options, _usable_pair, _validate_frequency_weights, @@ -717,7 +718,6 @@ def equals(self, other: "MicroDataFrame") -> bool: equal_weights = self.weights.equals(other.weights) return equal_values and equal_weights - @get_args_as_micro_series() def groupby(self, by: Union[str, List], *args, **kwargs) -> "MicroDataFrameGroupBy": """Returns a GroupBy object with MicroSeriesGroupBy objects for each column. @@ -728,23 +728,19 @@ def groupby(self, by: Union[str, List], *args, **kwargs) -> "MicroDataFrameGroup return: DataFrameGroupBy object with columns using weights rtype: DataFrameGroupBy """ - # Build the groupby on a *copy* that carries a ``__tmp_weights`` - # column. We used to set this column on ``self`` directly, which - # permanently leaked the weight column onto the caller's - # DataFrame — any later ``df.sum()`` or ``list(df.columns)`` - # would then include it. staged = pd.DataFrame(self).copy() - staged["__tmp_weights"] = np.asarray(self.weights.values, dtype=float) + weight_column = "__tmp_weights" + while weight_column in staged.columns: + weight_column += "_" + staged[weight_column] = np.asarray(self.weights.values, dtype=float) gb = staged.groupby(by, *args, **kwargs) - weights = copy.deepcopy(gb["__tmp_weights"]) - for col in staged.columns: # df.groupby(...)[col]s use weights - res = gb[col] - res.__class__ = MicroSeriesGroupBy - res._init() - res.weights = weights - setattr(gb, col, res) + # Share the same grouping for values and weights. Only the final + # result needs to put group keys in columns for as_index=False. + indexed = copy.copy(gb) + indexed.as_index = True + columns = [col for col in self.columns if col not in gb.exclusions] gb.__class__ = MicroDataFrameGroupBy - gb._init(by) + gb._init(indexed, indexed[weight_column], columns) return gb @get_args_as_micro_series() @@ -874,161 +870,48 @@ def __repr__(self) -> str: class MicroDataFrameGroupBy(pd.core.groupby.generic.DataFrameGroupBy): - def _init(self, by: Union[str, List]): - self._by = by - self.columns = list(self.obj.columns) - if isinstance(by, list): - for column in by: - self.columns.remove(column) - elif isinstance(by, str): - self.columns.remove(by) - self.columns.remove("__tmp_weights") - # Filter to only numeric columns + def _init(self, indexed_groupby, weights_groupby, columns): + self._indexed_groupby = indexed_groupby + self._weights_groupby = weights_groupby self.numeric_columns = [ - col for col in self.columns if pd.api.types.is_numeric_dtype(self.obj[col]) + col for col in columns if pd.api.types.is_numeric_dtype(self.obj[col]) ] - # Store reference to weights groupby for column selection - self._weights_groupby = copy.deepcopy(super().__getitem__("__tmp_weights")) - for fn_name in MicroSeries.SCALAR_FUNCTIONS: - - def get_fn(name): - def fn(*args, **kwargs): - results = {} - for col in self.numeric_columns: - try: - results[col] = getattr(getattr(self, col), name)( - *args, **kwargs - ) - except TypeError as exc: - # Skip columns whose dtype can't take this aggregation. - # Deliberately narrow: catching every Exception here also - # swallowed real errors (e.g. the ValueError from - # gini(negatives=...)) and returned a silently truncated - # result instead of raising. - logger.debug("skipping column %s in %s: %s", col, name, exc) - # Return plain DataFrame - aggregated results don't have - # per-row weights (weights were already applied) - return pd.DataFrame(results) if results else pd.DataFrame() - - return fn - - setattr(self, fn_name, get_fn(fn_name)) - for fn_name in MicroSeries.VECTOR_FUNCTIONS: - def get_fn(name) -> Callable: - def fn(*args, **kwargs) -> Union[pd.Series, pd.DataFrame]: - results = {} - for col in self.numeric_columns: - try: - results[col] = getattr(getattr(self, col), name)( - *args, **kwargs - ) - except TypeError as exc: - # Skip columns whose dtype can't take this aggregation. - # Deliberately narrow: catching every Exception here also - # swallowed real errors (e.g. the ValueError from - # gini(negatives=...)) and returned a silently truncated - # result instead of raising. - logger.debug("skipping column %s in %s: %s", col, name, exc) - # Return plain DataFrame - aggregated results don't have - # per-row weights (weights were already applied) - return pd.DataFrame(results) if results else pd.DataFrame() + def get_fn(name): + def fn(*args, **kwargs): + results = {} + for col in self.numeric_columns: + grouped = self._indexed_groupby[col] + grouped.__class__ = MicroSeriesGroupBy + grouped.weights = self._weights_groupby + grouped._init() + try: + results[col] = getattr(grouped, name)(*args, **kwargs) + except TypeError as exc: + logger.debug("skipping column %s in %s: %s", col, name, exc) + result = pd.DataFrame(results) + if not self.as_index and results: + return _grouped_result_as_columns(result) + return result - return fn + return fn + for fn_name in MicroSeries.FUNCTIONS: setattr(self, fn_name, get_fn(fn_name)) def __getitem__( self, key: Union[str, List] ) -> Union["MicroSeriesGroupBy", "MicroDataFrameGroupBy"]: - """Select columns from the groupby object while preserving weights. - - This ensures that operations like groupby(col)["y"].sum() or - groupby(col)[["y"]].sum() use weighted aggregation. - - :param key: Column name or list of column names - :return: MicroSeriesGroupBy for single column, MicroDataFrameGroupBy - for multiple columns - """ - if isinstance(key, str): - # Single column - return MicroSeriesGroupBy - result = super().__getitem__(key) + """Select grouped columns while preserving their row weights.""" + result = super().__getitem__(key) + if isinstance(result, pd.core.groupby.generic.SeriesGroupBy): + indexed = None if self.as_index else self._indexed_groupby[key] result.__class__ = MicroSeriesGroupBy - result._init() result.weights = self._weights_groupby - return result + result._init(indexed) else: - # Multiple columns - return a new MicroDataFrameGroupBy - # with only the selected columns - result = super().__getitem__(key) result.__class__ = MicroDataFrameGroupBy - # Re-initialize with the subset of columns - result._by = self._by - result.columns = list(key) if hasattr(key, "__iter__") else [key] - result.numeric_columns = [ - col - for col in result.columns - if pd.api.types.is_numeric_dtype(result.obj[col]) - ] - result._weights_groupby = self._weights_groupby - # Set up the column attributes as MicroSeriesGroupBy - for col in result.columns: - col_gb = super().__getitem__(col) - col_gb.__class__ = MicroSeriesGroupBy - col_gb._init() - col_gb.weights = self._weights_groupby - setattr(result, col, col_gb) - # Set up the scalar and vector functions - for fn_name in MicroSeries.SCALAR_FUNCTIONS: - - def get_scalar_fn(name, res): - def fn(*args, **kwargs): - results = {} - for col in res.numeric_columns: - try: - results[col] = getattr(getattr(res, col), name)( - *args, **kwargs - ) - except TypeError as exc: - # Skip columns whose dtype can't take this aggregation. - # Deliberately narrow: catching every Exception here also - # swallowed real errors (e.g. the ValueError from - # gini(negatives=...)) and returned a silently truncated - # result instead of raising. - logger.debug( - "skipping column %s in %s: %s", col, name, exc - ) - # Return plain DataFrame - aggregated results don't - # have per-row weights (weights were already applied) - return pd.DataFrame(results) if results else pd.DataFrame() - - return fn - - setattr(result, fn_name, get_scalar_fn(fn_name, result)) - for fn_name in MicroSeries.VECTOR_FUNCTIONS: - - def get_vector_fn(name, res): - def fn(*args, **kwargs): - results = {} - for col in res.numeric_columns: - try: - results[col] = getattr(getattr(res, col), name)( - *args, **kwargs - ) - except TypeError as exc: - # Skip columns whose dtype can't take this aggregation. - # Deliberately narrow: catching every Exception here also - # swallowed real errors (e.g. the ValueError from - # gini(negatives=...)) and returned a silently truncated - # result instead of raising. - logger.debug( - "skipping column %s in %s: %s", col, name, exc - ) - # Return plain DataFrame - aggregated results don't - # have per-row weights (weights were already applied) - return pd.DataFrame(results) if results else pd.DataFrame() - - return fn - - setattr(result, fn_name, get_vector_fn(fn_name, result)) - return result + result._init( + self._indexed_groupby, self._weights_groupby, result._selection_list + ) + return result diff --git a/microdf/microseries.py b/microdf/microseries.py index 36ece1d..236e155 100644 --- a/microdf/microseries.py +++ b/microdf/microseries.py @@ -1190,73 +1190,65 @@ def __repr__(self) -> str: ) +def _grouped_result_as_columns(result: pd.DataFrame) -> pd.DataFrame: + keys = result.iloc[:, :0].reset_index(allow_duplicates=True) + # An explicitly selected grouping column can also be a result column. + keys = keys.loc[:, ~keys.columns.isin(result.columns)] + return pd.concat([keys, result.reset_index(drop=True)], axis=1) + + class MicroSeriesGroupBy(pd.core.groupby.generic.SeriesGroupBy): - def _init(self): - def _weighted_agg(name) -> Callable: - def via_micro_series(row, *args, **kwargs): - return getattr(MicroSeries(row.a, weights=row.w), name)(*args, **kwargs) + def _init(self, indexed_groupby=None): + grouped = self if indexed_groupby is None else indexed_groupby + def _weighted_agg(name) -> Callable: fn = getattr(MicroSeries, name) @wraps(fn) def _weighted_agg_fn(*args, **kwargs) -> Union[pd.Series, pd.DataFrame]: - arrays = self.apply(np.array) + arrays = grouped.apply(np.array) weights = self.weights.apply(np.array) - df = pd.DataFrame(dict(a=arrays, w=weights)) - is_array = len(args) > 0 and hasattr(args[0], "__len__") - if ( - name in MicroSeries.SCALAR_FUNCTIONS - or name in MicroSeries.AGNOSTIC_FUNCTIONS - and not is_array - ): - result = df.agg( - lambda row: via_micro_series(row, *args, **kwargs), - axis=1, - ) - elif ( - name in MicroSeries.VECTOR_FUNCTIONS - or name in MicroSeries.AGNOSTIC_FUNCTIONS - and is_array - ): - if name in MicroSeries.AGNOSTIC_FUNCTIONS and not df.empty: - # Concatenate values without keys: concat rejects missing - # MultiIndex keys even when groupby(dropna=False) retains - # them. Reuse the grouping levels and codes so missing - # labels keep the same representation as scalar results. - results = [ - via_micro_series(row, *args, **kwargs) - for _, row in df.iterrows() - ] - result = pd.concat(results) - group_index = ( - df.index - if isinstance(df.index, pd.MultiIndex) - else pd.MultiIndex.from_arrays([df.index]) - ) - quantile_codes, quantile_levels = result.index.factorize( - sort=False - ) - result.index = pd.MultiIndex( - levels=[*group_index.levels, quantile_levels], - codes=[ - codes.repeat(len(results[0])) - for codes in group_index.codes - ] - + [quantile_codes], - names=[*df.index.names, result.index.name], - # Existing group codes are valid; checking would - # rewrite their retained missing labels to -1. - verify_integrity=False, - ) - return result - result = df.apply( - lambda row: via_micro_series(row, *args, **kwargs), - axis=1, - ) - return result.stack() + results = [ + fn(MicroSeries(values, weights=group_weights), *args, **kwargs) + for values, group_weights in zip(arrays, weights) + ] + vector = name in MicroSeries.VECTOR_FUNCTIONS + if name in MicroSeries.AGNOSTIC_FUNCTIONS: + q = args[0] if args else kwargs.get("q") + vector = np.ndim(q) != 0 + + if vector: + result = self._combine_vectors(arrays.index, results) + else: + result = pd.Series(results, index=arrays.index) + if not self.as_index: + return _grouped_result_as_columns(result.to_frame(self.obj.name)) return result return _weighted_agg_fn for fn_name in MicroSeries.FUNCTIONS: setattr(self, fn_name, _weighted_agg(fn_name)) + + @staticmethod + def _combine_vectors(groups, results) -> pd.Series: + # Concatenate group results directly to retain NaN values and avoid + # padding shorter groups. The last level holds local row positions or q. + result = ( + pd.concat([pd.Series(value) for value in results]) + if results + else pd.Series(dtype=float) + ) + if not isinstance(groups, pd.MultiIndex): + groups = pd.MultiIndex.from_arrays([groups]) + lengths = [len(value) for value in results] + codes, levels = result.index.factorize(sort=False) + result.index = pd.MultiIndex( + levels=[*groups.levels, levels], + codes=[group_codes.repeat(lengths) for group_codes in groups.codes] + + [codes], + names=[*groups.names, result.index.name], + # Keep the original codes for retained missing grouping keys. + verify_integrity=False, + ) + return result diff --git a/microdf/tests/test_groupby_reductions.py b/microdf/tests/test_groupby_reductions.py new file mode 100644 index 0000000..d7a7785 --- /dev/null +++ b/microdf/tests/test_groupby_reductions.py @@ -0,0 +1,225 @@ +import numpy as np +import pandas as pd +import pytest + +from microdf import MicroDataFrame, MicroSeries + + +SCALAR_ARGS = { + "bottom_x_pct_share": ((0.5,), {}), + "top_x_pct_share": ((0.1,), {}), + "var": ((), {"ddof": 0}), +} +REDUCTIONS = [ + pytest.param(name, *SCALAR_ARGS.get(name, ((), {})), id=name) + for name in MicroSeries.SCALAR_FUNCTIONS +] + [ + pytest.param("quantile", (0.25,), {}, id="quantile-scalar"), + pytest.param("quantile", ([0.1, 0.9],), {}, id="quantile-list"), +] +SPELLINGS = ["series", "list", "frame"] +VARIATIONS = [ + "one-key", + "two-keys", + "unsorted", + "missing-keys", + "categorical-observed", + "categorical-unobserved", + "non-default-index", + "duplicate-index", + "zero-weights", + "nan-values", + "numeric-key", + "as-index-false", + "array-key", + "non-numeric-value", +] + + +def make_frame(variation): + data = {"g": ["b", "a", "b", "a", "b", "a"], "x": [2.0, 6.0, 9.0, 4.0, 11.0, 1.0]} + data["y"] = [30.0, 25.0, 20.0, 15.0, 10.0, 5.0] + weights = [2, 7, 1, 4, 8, 3] + keys, index, options = ["g"], None, {} + if variation in {"two-keys", "missing-keys"}: + keys.append("h") + data["h"] = [1, 2, 1, 2, 2, 1] + if variation == "unsorted": + options["sort"] = False + if variation == "missing-keys": + data["g"][2] = None + data["h"][3] = np.nan + options["dropna"] = False + if variation.startswith("categorical"): + data["g"] = pd.Categorical(data["g"], categories=["a", "b", "unused"]) + options["observed"] = variation == "categorical-observed" + if variation == "non-default-index": + index = pd.Index([30, 10, 70, 50, 90, 20], name="row") + if variation == "duplicate-index": + index = pd.Index([30, 30, 70, 70, 90, 30], name="row") + if variation == "zero-weights": + weights[::2] = [0, 0, 0] + if variation == "nan-values": + data["x"][2] = np.nan + if variation == "numeric-key": + data["g"] = [2, 1, 2, 1, 2, 1] + if variation == "as-index-false": + options["as_index"] = False + if variation == "non-numeric-value": + data["text"] = ["example"] * 6 + return MicroDataFrame(data, index=index, weights=weights), keys, options + + +def select(grouped, spelling, column="x"): + if spelling == "series": + return grouped[column] + if spelling == "list": + return grouped[[column]] + return grouped + + +def masks(frame, keys, groups): + for group in groups: + values = (group,) if len(keys) == 1 else group + mask = np.ones(len(frame), dtype=bool) + for key, value in zip(keys, values): + key_values = pd.Series(frame[key]) + match = key_values.isna() if pd.isna(value) else key_values.eq(value) + mask &= match.to_numpy() + yield mask + + +def masked_reduction(frame, keys, groups, index, columns, name, args, kwargs): + result = {} + for column in columns: + series = frame[column] + values = [ + getattr(series[mask], name)(*args, **kwargs) + for mask in masks(frame, keys, groups) + ] + if name == "quantile" and isinstance(args[0], list): + values = np.concatenate(values) + result[column] = pd.Series(values, index=index) + return pd.DataFrame(result) + + +@pytest.mark.parametrize("variation", VARIATIONS) +@pytest.mark.parametrize("spelling", SPELLINGS) +@pytest.mark.parametrize("name,args,kwargs", REDUCTIONS) +def test_reductions_match_masked_groups(variation, spelling, name, args, kwargs): + frame, keys, options = make_frame(variation) + columns = ["x", "y"] if spelling == "frame" else ["x"] + indexed_options = {**options, "as_index": True} + results = [] + # Reverse rows and weights together. Keep source labels, including duplicates. + reversed_frame = frame.iloc[::-1] + pd.testing.assert_series_equal(reversed_frame.weights, frame.weights.iloc[::-1]) + for ordered in (frame, reversed_frame): + original = pd.DataFrame(ordered).copy(deep=True) + weights = ordered.weights.copy(deep=True) + by = keys[0] if len(keys) == 1 else keys + if variation == "array-key": + by = original["g"].to_numpy() + plain_groupby = original.groupby(by, **indexed_options) + groups = plain_groupby.size().index + # pandas supplies result labels and order. Values come from the masks. + index = groups + if name == "quantile" and isinstance(args[0], list): + index = plain_groupby["x"].quantile(args[0]).index + grouped = ordered.groupby(by, **options) + pd.testing.assert_index_equal(ordered.columns, original.columns) + pd.testing.assert_series_equal(ordered.weights, weights) + method = getattr(select(grouped, spelling), name) + if variation == "zero-weights" and name == "mean": + # The masked MicroSeries raises when np.average sees zero total weight. + with pytest.raises(ZeroDivisionError, match="Weights sum to zero"): + masked_reduction( + ordered, keys, groups, index, columns, name, args, kwargs + ) + with pytest.raises(ZeroDivisionError, match="Weights sum to zero"): + method(*args, **kwargs) + else: + expected = masked_reduction( + ordered, keys, groups, index, columns, name, args, kwargs + ) + actual = method(*args, **kwargs) + if not options.get("as_index", True): + # Use named grouping columns and a RangeIndex, as with pandas. + flattened = expected.reset_index() + pd.testing.assert_frame_equal(actual, flattened, check_dtype=False) + actual = actual.set_index( + list(flattened.columns[: expected.index.nlevels]) + ) + elif spelling == "series": + pd.testing.assert_series_equal( + actual, expected["x"].rename(None), check_dtype=False + ) + actual = actual.to_frame("x") + else: + pd.testing.assert_frame_equal(actual, expected, check_dtype=False) + results.append(actual.sort_index()) + pd.testing.assert_frame_equal(pd.DataFrame(ordered), original) + pd.testing.assert_series_equal(ordered.weights, weights) + if results: + pd.testing.assert_frame_equal(*results) + + +@pytest.mark.parametrize("spelling", SPELLINGS) +@pytest.mark.parametrize("name", MicroSeries.VECTOR_FUNCTIONS) +@pytest.mark.parametrize("unequal", [False, True], ids=["equal-size", "unequal-size"]) +def test_grouped_vectors_match_masked_groups(spelling, name, unequal): + keys = ["b", "a", "b", "b" if unequal else "a"] + values = [2.0, 5.0, np.nan if unequal else 2.0, 1.0] + frame = MicroDataFrame( + {"g": keys, "x": values}, + index=[40, 10, 40, 70], + weights=[2, 3, 7, 5], + ) + # Vector output uses group-local positions even with duplicate source labels. + # The unequal-size case also has a missing value. + result = getattr(select(frame.groupby("g"), spelling), name)() + values, labels = [], [] + for key in ("a", "b"): + subset = frame["x"][pd.Series(frame["g"]).eq(key).to_numpy()] + expected = getattr(subset, name)() + values.extend(np.asarray(expected)) + labels.extend((key, position) for position in range(len(subset))) + expected = pd.Series( + values, index=pd.MultiIndex.from_tuples(labels, names=["g", None]) + ) + if spelling == "series": + pd.testing.assert_series_equal(result, expected) + else: + pd.testing.assert_frame_equal(result, expected.to_frame("x")) + + +@pytest.mark.parametrize("spelling", ["list", "frame"]) +def test_frame_quantile_uses_group_weights(spelling): + frame = MicroDataFrame({"g": [1, 1], "x": [1, 9]}, weights=[3, 1]) + result = select(frame.groupby("g"), spelling).quantile(0.25) + assert result.loc[1, "x"] == 1 + + +def test_grouped_quantile_accepts_list_by_keyword(): + frame = MicroDataFrame({"g": ["a", "a"], "x": [1, 9]}, weights=[3, 1]) + result = frame.groupby("g")["x"].quantile(q=[0.1, 0.9]) + assert result.index.tolist() == [("a", 0.1), ("a", 0.9)] + assert result.tolist() == [1, 9] + + +def test_grouped_sum_excludes_the_numeric_key(): + frame = MicroDataFrame({"g": [1], "x": [3]}, weights=[2]) + assert frame.groupby("g").sum().to_dict() == {"x": {1: 6}} + + +@pytest.mark.parametrize("spelling", SPELLINGS) +def test_grouped_sum_keeps_key_column_with_as_index_false(spelling): + frame = MicroDataFrame({"g": ["a"], "x": [3]}, weights=[2]) + result = select(frame.groupby("g", as_index=False), spelling).sum() + assert result.to_dict("list") == {"g": ["a"], "x": [6]} + + +@pytest.mark.parametrize("column", ["__tmp_weights", "sum", 5]) +def test_grouped_sum_handles_column_labels(column): + frame = MicroDataFrame({"g": ["a"], column: [3]}, weights=[2]) + assert frame.groupby("g").sum().to_dict() == {column: {"a": 6}}