Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/4007.fixed.md
Original file line number Diff line number Diff line change
@@ -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.
5 changes: 5 additions & 0 deletions microdf/_weights.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
25 changes: 14 additions & 11 deletions microdf/microdataframe.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand All @@ -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.
Expand Down
51 changes: 51 additions & 0 deletions microdf/tests/test_row_weight_invariant.py
Original file line number Diff line number Diff line change
@@ -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)
Loading