-
-
Notifications
You must be signed in to change notification settings - Fork 18.6k
BUG: Fix remaining cases of groupby(...).transform with dropna=True #46367
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 19 commits
2143c59
deb3edb
04a2a6b
ad7bf3e
39e1438
7a4a99b
f234a89
d1eeb65
e57025d
be2f45c
8e5df01
2d79a0f
e2f3080
d9da864
b973af0
67ffb60
e31041d
60e60b0
04293a7
9a6dc3c
d7bb828
6571291
a8f524b
2a02de0
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -98,15 +98,25 @@ | |
class WrappedCythonOp: | ||
""" | ||
Dispatch logic for functions defined in _libs.groupby | ||
|
||
Parameters | ||
---------- | ||
kind: str | ||
Whether the operation is an aggregate or transform. | ||
how: str | ||
Operation name, e.g. "mean". | ||
has_dropped_na: bool | ||
True precisely when dropna=True and the grouper contains a null value. | ||
""" | ||
|
||
# Functions for which we do _not_ attempt to cast the cython result | ||
# back to the original dtype. | ||
cast_blocklist = frozenset(["rank", "count", "size", "idxmin", "idxmax"]) | ||
|
||
def __init__(self, kind: str, how: str) -> None: | ||
def __init__(self, kind: str, how: str, has_dropped_na: bool) -> None: | ||
self.kind = kind | ||
self.how = how | ||
self.has_dropped_na = has_dropped_na | ||
|
||
_CYTHON_FUNCTIONS = { | ||
"aggregate": { | ||
|
@@ -194,7 +204,9 @@ def _get_cython_vals(self, values: np.ndarray) -> np.ndarray: | |
values = ensure_float64(values) | ||
|
||
elif values.dtype.kind in ["i", "u"]: | ||
if how in ["add", "var", "prod", "mean", "ohlc"]: | ||
if how in ["add", "var", "prod", "mean", "ohlc"] or ( | ||
self.kind == "transform" and self.has_dropped_na | ||
): | ||
# result may still include NaN, so we have to cast | ||
values = ensure_float64(values) | ||
|
||
|
@@ -582,6 +594,10 @@ def _call_cython_op( | |
|
||
result = result.T | ||
|
||
if self.how == "rank" and self.has_dropped_na: | ||
# TODO: Wouldn't need this if group_rank supported mask | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. would this be a matter of supporting a mask arg in the libgroupby function, or would this be just for Nullable dtype? bc i have a branch on deck that does the former There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The former - I believe rank had to be singled out here because it was the one transform that didn't support a mask arg. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. @rhshadrach mask just got added to group_rank, but commenting this out causes a few failures. is more needed? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This comment was incorrect; opened #46953 |
||
result = np.where(comp_ids < 0, np.nan, result) | ||
|
||
if self.how not in self.cast_blocklist: | ||
# e.g. if we are int64 and need to restore to datetime64/timedelta64 | ||
# "rank" is the only member of cast_blocklist we get here | ||
|
@@ -959,7 +975,7 @@ def _cython_operation( | |
""" | ||
assert kind in ["transform", "aggregate"] | ||
|
||
cy_op = WrappedCythonOp(kind=kind, how=how) | ||
cy_op = WrappedCythonOp(kind=kind, how=how, has_dropped_na=self.has_dropped_na) | ||
|
||
ids, _, _ = self.group_info | ||
ngroups = self.ngroups | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -168,6 +168,10 @@ def test_transform_axis_1(request, transformation_func): | |
# TODO(2.0) Remove after pad/backfill deprecation enforced | ||
transformation_func = maybe_normalize_deprecated_kernels(transformation_func) | ||
|
||
if transformation_func == "ngroup": | ||
msg = "ngroup fails with axis=1: #45986" | ||
request.node.add_marker(pytest.mark.xfail(reason=msg)) | ||
|
||
warn = None | ||
if transformation_func == "tshift": | ||
warn = FutureWarning | ||
|
@@ -383,6 +387,15 @@ def test_transform_transformation_func(request, transformation_func): | |
elif transformation_func == "fillna": | ||
test_op = lambda x: x.transform("fillna", value=0) | ||
mock_op = lambda x: x.fillna(value=0) | ||
elif transformation_func == "ngroup": | ||
test_op = lambda x: x.transform("ngroup") | ||
counter = -1 | ||
|
||
def mock_op(x): | ||
nonlocal counter | ||
counter += 1 | ||
return Series(counter, index=x.index) | ||
|
||
elif transformation_func == "tshift": | ||
msg = ( | ||
"Current behavior of groupby.tshift is inconsistent with other " | ||
|
@@ -394,10 +407,14 @@ def test_transform_transformation_func(request, transformation_func): | |
mock_op = lambda x: getattr(x, transformation_func)() | ||
|
||
result = test_op(df.groupby("A")) | ||
groups = [df[["B"]].iloc[:4], df[["B"]].iloc[4:6], df[["B"]].iloc[6:]] | ||
expected = concat([mock_op(g) for g in groups]) | ||
# pass the group in same order as iterating `for ... in df.groupby(...)` | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. can you link the issue/PR here There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Within this test, the issue number is on L374. |
||
# but reorder to match df's index since this is a transform | ||
groups = [df[["B"]].iloc[4:6], df[["B"]].iloc[6:], df[["B"]].iloc[:4]] | ||
expected = concat([mock_op(g) for g in groups]).sort_index() | ||
# sort_index does not preserve the freq | ||
expected = expected.set_axis(df.index) | ||
|
||
if transformation_func == "cumcount": | ||
if transformation_func in ("cumcount", "ngroup"): | ||
tm.assert_series_equal(result, expected) | ||
else: | ||
tm.assert_frame_equal(result, expected) | ||
|
@@ -1122,10 +1139,6 @@ def test_transform_agg_by_name(request, reduction_func, obj): | |
func = reduction_func | ||
g = obj.groupby(np.repeat([0, 1], 3)) | ||
|
||
if func == "ngroup": # GH#27468 | ||
request.node.add_marker( | ||
pytest.mark.xfail(reason="TODO: g.transform('ngroup') doesn't work") | ||
) | ||
if func == "corrwith" and isinstance(obj, Series): # GH#32293 | ||
request.node.add_marker( | ||
pytest.mark.xfail(reason="TODO: implement SeriesGroupBy.corrwith") | ||
|
@@ -1137,8 +1150,8 @@ def test_transform_agg_by_name(request, reduction_func, obj): | |
# this is the *definition* of a transformation | ||
tm.assert_index_equal(result.index, obj.index) | ||
|
||
if func != "size" and obj.ndim == 2: | ||
# size returns a Series, unlike other transforms | ||
if func not in ("ngroup", "size") and obj.ndim == 2: | ||
# size/ngroup return a Series, unlike other transforms | ||
tm.assert_index_equal(result.columns, obj.columns) | ||
|
||
# verify that values were broadcasted across each group | ||
|
@@ -1312,7 +1325,7 @@ def test_null_group_lambda_self(sort, dropna): | |
|
||
def test_null_group_str_reducer(request, dropna, reduction_func): | ||
# GH 17093 | ||
if reduction_func in ("corrwith", "ngroup"): | ||
if reduction_func == "corrwith": | ||
msg = "incorrectly raises" | ||
request.node.add_marker(pytest.mark.xfail(reason=msg)) | ||
index = [1, 2, 3, 4] # test transform preserves non-standard index | ||
|
@@ -1357,31 +1370,11 @@ def test_null_group_str_reducer(request, dropna, reduction_func): | |
tm.assert_equal(result, expected) | ||
|
||
|
||
def test_null_group_str_transformer( | ||
request, using_array_manager, dropna, transformation_func | ||
): | ||
def test_null_group_str_transformer(request, dropna, transformation_func): | ||
# GH 17093 | ||
xfails_block = ( | ||
"cummax", | ||
"cummin", | ||
"cumsum", | ||
"fillna", | ||
"rank", | ||
"backfill", | ||
"ffill", | ||
"bfill", | ||
"pad", | ||
) | ||
xfails_array = ("cummax", "cummin", "cumsum", "fillna", "rank") | ||
if transformation_func == "tshift": | ||
msg = "tshift requires timeseries" | ||
request.node.add_marker(pytest.mark.xfail(reason=msg)) | ||
elif dropna and ( | ||
(not using_array_manager and transformation_func in xfails_block) | ||
or (using_array_manager and transformation_func in xfails_array) | ||
): | ||
msg = "produces incorrect results when nans are present" | ||
request.node.add_marker(pytest.mark.xfail(reason=msg)) | ||
args = (0,) if transformation_func == "fillna" else () | ||
df = DataFrame({"A": [1, 1, np.nan], "B": [1, 2, 2]}, index=[1, 2, 3]) | ||
gb = df.groupby("A", dropna=dropna) | ||
|
@@ -1419,10 +1412,6 @@ def test_null_group_str_reducer_series(request, dropna, reduction_func): | |
msg = "corrwith not implemented for SeriesGroupBy" | ||
request.node.add_marker(pytest.mark.xfail(reason=msg)) | ||
|
||
if reduction_func == "ngroup": | ||
msg = "ngroup fails" | ||
request.node.add_marker(pytest.mark.xfail(reason=msg)) | ||
|
||
# GH 17093 | ||
index = [1, 2, 3, 4] # test transform preserves non-standard index | ||
ser = Series([1, 2, 2, 3], index=index) | ||
|
@@ -1463,21 +1452,11 @@ def test_null_group_str_reducer_series(request, dropna, reduction_func): | |
tm.assert_series_equal(result, expected) | ||
|
||
|
||
@pytest.mark.filterwarnings("ignore:tshift is deprecated:FutureWarning") | ||
def test_null_group_str_transformer_series(request, dropna, transformation_func): | ||
# GH 17093 | ||
if transformation_func == "tshift": | ||
msg = "tshift requires timeseries" | ||
request.node.add_marker(pytest.mark.xfail(reason=msg)) | ||
elif dropna and transformation_func in ( | ||
"cummax", | ||
"cummin", | ||
"cumsum", | ||
"fillna", | ||
"rank", | ||
): | ||
msg = "produces incorrect results when nans are present" | ||
request.node.add_marker(pytest.mark.xfail(reason=msg)) | ||
args = (0,) if transformation_func == "fillna" else () | ||
ser = Series([1, 2, 2], index=[1, 2, 3]) | ||
gb = ser.groupby([1, 1, np.nan], dropna=dropna) | ||
|
@@ -1501,4 +1480,10 @@ def test_null_group_str_transformer_series(request, dropna, transformation_func) | |
msg = f"{transformation_func} is deprecated" | ||
with tm.assert_produces_warning(warn, match=msg): | ||
result = gb.transform(transformation_func, *args) | ||
tm.assert_equal(result, expected) | ||
if dropna and transformation_func == "fillna": | ||
# GH#46369 - result name is the group; remove this block when fixed. | ||
tm.assert_equal(result, expected, check_names=False) | ||
# This should be None | ||
assert result.name == 1.0 | ||
else: | ||
tm.assert_equal(result, expected) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
maybe be worth commenting on each of these what is changing (e.g. like you did for [3])