From 5c9caa05e4a504d7f08eb447563b530fa2b21ef2 Mon Sep 17 00:00:00 2001 From: Max Ghenis <6076111+MaxGhenis@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:56:39 -0500 Subject: [PATCH] Preserve row weights across reindex and merge --- changelog.d/4007.fixed.md | 1 + microdf/_weights.py | 5 +++ microdf/microdataframe.py | 25 ++++++----- microdf/tests/test_row_weight_invariant.py | 51 ++++++++++++++++++++++ 4 files changed, 71 insertions(+), 11 deletions(-) create mode 100644 changelog.d/4007.fixed.md create mode 100644 microdf/tests/test_row_weight_invariant.py diff --git a/changelog.d/4007.fixed.md b/changelog.d/4007.fixed.md new file mode 100644 index 00000000..74ace16d --- /dev/null +++ b/changelog.d/4007.fixed.md @@ -0,0 +1 @@ +Preserve row weights when reindexing both axes and preserve missing weights on matched merge rows. Reject direct pandas merges that can discard weights and direct users to MicroDataFrame.merge. diff --git a/microdf/_weights.py b/microdf/_weights.py index 3dd72456..66c7c793 100644 --- a/microdf/_weights.py +++ b/microdf/_weights.py @@ -30,6 +30,11 @@ def finalize_weights(result, source, method, previous_weights): "Cannot transpose row weights onto columns. " "Convert to a pandas DataFrame first and supply explicit result weights." ) + if method == "merge": + raise ValueError( + "Cannot propagate row weights through pandas.merge. " + "Use MicroDataFrame.merge to preserve left row weights." + ) if method == "concat": objects = source.objs if not all(isinstance(obj, WeightPropagationMixin) for obj in objects): diff --git a/microdf/microdataframe.py b/microdf/microdataframe.py index 32be4a00..61efbbff 100644 --- a/microdf/microdataframe.py +++ b/microdf/microdataframe.py @@ -82,6 +82,11 @@ def __finalize__(self, other, method=None, **kwargs): super().__finalize__(other, method=method, **kwargs) return finalize_weights(self, other, method, previous) + def _reindex_multi(self, *args, **kwargs): + # The pandas fast path can construct a result without finalizing it. + result = super()._reindex_multi(*args, **kwargs) + return result.__finalize__(self, method="reindex") + def cov( self, min_periods: Optional[int] = None, @@ -662,16 +667,14 @@ def merge( :param validate: If specified, checks if merge is of specified type. :return: MicroDataFrame with merged data. """ - # Attach the left weights as a temporary column so pandas' merge - # propagates them onto every surviving output row (including - # many-to-many row duplications, inner-join filtering, and - # left-with-missing NaNs). We then strip the column back off. + # Carry left row positions through the join so unmatched rows can be + # distinguished from matched rows whose weights are missing. tmp = "__microdf_weights__" # Avoid clobbering if this exact name is already used. while tmp in self.columns or tmp in right.columns: tmp += "_" left_df = pd.DataFrame(self).copy() - left_df[tmp] = np.asarray(self.weights.values, dtype=float) + left_df[tmp] = np.arange(len(self)) res = left_df.merge( right, how=how, @@ -686,12 +689,12 @@ def merge( indicator=indicator, validate=validate, ) - # Pull out the propagated weights. Rows with no left match in a - # right/outer join get NaN weight — fill with 0 so they don't - # poison later aggregations (a user who needs a different - # convention can override afterwards). - merged_weights = res[tmp].fillna(0).to_numpy(dtype=float) - res = res.drop(columns=[tmp]) + positions = res.pop(tmp) + matched = positions.notna() + merged_weights = np.zeros(len(res), dtype=float) + merged_weights[matched] = self.weights.to_numpy()[ + positions[matched].to_numpy(dtype=np.intp) + ] out = MicroDataFrame(res, weights=merged_weights) # Ensure the weights Series aligns with res.index regardless of # the default-RangeIndex behavior of set_weights. diff --git a/microdf/tests/test_row_weight_invariant.py b/microdf/tests/test_row_weight_invariant.py new file mode 100644 index 00000000..f10e7403 --- /dev/null +++ b/microdf/tests/test_row_weight_invariant.py @@ -0,0 +1,51 @@ +"""Hold row weights to their source positions through pandas row operations.""" + +import numpy as np +import pandas as pd +import pytest + +from microdf import MicroDataFrame, MicroSeries + + +@pytest.mark.parametrize("target", [[1, 0], [1]]) +def test_reindex_rows_and_columns_preserves_weights(target): + source = MicroDataFrame({"row_id": [0, 1], "key": [0, 0]}, weights=[1000, 1001]) + + result = source.reindex(index=target, columns=["key", "row_id"]) + + assert list(result.columns) == ["key", "row_id"] + np.testing.assert_array_equal(result["row_id"], target) + np.testing.assert_array_equal(result.weights.to_numpy(), 1000 + np.array(target)) + assert result.weights.index.equals(result.index) + + +def test_reindex_rows_and_columns_rejects_new_rows(): + source = MicroDataFrame({"row_id": [0, 1], "key": [0, 0]}, weights=[1000, 1001]) + + with pytest.raises(ValueError, match="propagate weights"): + source.reindex(index=[1, 2], columns=["key", "row_id"]) + + +@pytest.mark.parametrize("kind", [MicroDataFrame, MicroSeries]) +def test_pandas_merge_rejects_weight_loss(kind): + if kind is MicroDataFrame: + left = kind({"row_id": [0, 1], "key": [0, 0]}, weights=[1000, 1001]) + else: + left = kind([0, 1], name="key", weights=[1000, 1001]) + right = MicroDataFrame({"join_key": [0, 1, 0, 1]}, weights=[1002, 1003, 1004, 1005]) + + with pytest.raises(ValueError, match=r"MicroDataFrame\.merge"): + pd.merge(left, right, left_on="key", right_on="join_key") + + +def test_merge_distinguishes_a_missing_weight_from_an_unmatched_row(): + left = MicroDataFrame({"row_id": [0, 1], "key": [0, 0]}, weights=[np.nan, 1001]) + right = pd.DataFrame({"key": [0, 0, 1]}) + + result = left.merge(right, on="key", how="outer") + + np.testing.assert_array_equal(result["row_id"], [0, 0, 1, 1, np.nan]) + np.testing.assert_array_equal( + result.weights.to_numpy(), [np.nan, np.nan, 1001, 1001, 0] + ) + assert result.weights.index.equals(result.index)