Skip to content

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

Merged
merged 24 commits into from
Mar 22, 2022

Conversation

rhshadrach
Copy link
Member

@rhshadrach rhshadrach requested a review from jbrockmendel March 15, 2022 03:28
@@ -969,7 +985,7 @@ def _cython_operation(
"""
assert kind in ["transform", "aggregate"]

cy_op = WrappedCythonOp(kind=kind, how=how)
cy_op = WrappedCythonOp(grouper=self, kind=kind, how=how)
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jbrockmendel - It would suffice to pass self.has_dropped_na instead of the full grouper here, wasn't sure if there was a preference one way or the others.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd much rather just has_dropped_na be part of WrappedCythonOop's state

@@ -592,6 +604,10 @@ def _call_cython_op(

result = result.T

if self.how == "rank" and self.grouper.has_dropped_na:
# TODO: Wouldn't need this if group_rank supported mask
Copy link
Member

Choose a reason for hiding this comment

The 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

Copy link
Member Author

Choose a reason for hiding this comment

The 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.

Copy link
Member

Choose a reason for hiding this comment

The 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?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This comment was incorrect; opened #46953

@@ -462,6 +469,11 @@ def _cython_op_ndim_compat(
# otherwise we have OHLC
return res.T

if self.kind == "transform" and self.grouper.has_dropped_na:
mask = comp_ids == -1
# make mask 2d
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can this be rolled into the mask-reshaping done above?

Copy link
Member Author

@rhshadrach rhshadrach Mar 16, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This block turned out to not be necessary. It will be removed.

@@ -260,6 +264,9 @@ def _get_output_shape(self, ngroups: int, values: np.ndarray) -> Shape:
def _get_out_dtype(self, dtype: np.dtype) -> np.dtype:
how = self.how

if self.kind == "transform" and self.grouper.has_dropped_na:
dtype = ensure_dtype_can_hold_na(dtype)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ATM we do something similar to this L578-L591. could this be rolled into that? (admittedly thats a bit messy so this may just b A Better Solution)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems better to me to determine the result dtype upfront, rather than cast after, as much as possible.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i dont have an opinion on before vs after so am happy to defer to you, but do strongly prefer doing things Just One Way.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes sense - I didn't realize that my change to _get_cython_vals actually makes values float, and so this is indeed not necessary at all.

@jbrockmendel
Copy link
Member

Last thought before I go guzzle some caffeine: this looks tangentially related to #43943. Might be something worth salvaging from that.

@jreback jreback added this to the 1.5 milestone Mar 16, 2022
In [3]: df.groupby('a', dropna=True).transform(lambda x: x.sum())
Out[3]:
b
0 5
1 5

In [3]: df.groupby('a', dropna=True).transform('ffill')
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

add a comment here on the casting of the fill value

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you're saying to explain why the old result comes out as -9223372036854775808, which is np.nan when interpreted as an integer. Will do.

return self._python_apply_general(curried, self._obj_with_exclusions)
result = self._python_apply_general(curried, self._obj_with_exclusions)

if result.ndim == 1 and self.obj.ndim == 1 and result.name != self.obj.name:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

result.name != self.obj.name will be wrong with np.nan (and will raise with pd.NA)

Copy link
Member Author

@rhshadrach rhshadrach Mar 18, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Doh, thanks. This highlights the fact that we shouldn't be fixing this here, but rather the logic in wrapping the apply results. I didn't want this PR spreading out to that method though. I've opened #46369 for this; I'm thinking here we ignore testing the name, and fix properly.

@rhshadrach
Copy link
Member Author

Thanks for all the feedback @jbrockmendel and @jreback - ready for another review.

Copy link
Contributor

@jreback jreback left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks good. pls rebas some small comments. ping on greeen.

@@ -83,32 +83,41 @@ did not have the same index as the input.

.. code-block:: ipython

In [3]: df.groupby('a', dropna=True).transform('sum')
Copy link
Contributor

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])

@@ -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(...)`
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you link the issue/PR here

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Within this test, the issue number is on L374.

@jreback jreback merged commit 8714948 into pandas-dev:main Mar 22, 2022
@jreback
Copy link
Contributor

jreback commented Mar 22, 2022

thanks @rhshadrach

@rhshadrach rhshadrach deleted the transform_dropna branch April 10, 2022 22:23
@rhshadrach rhshadrach added the Missing-data np.nan, pd.NaT, pd.NA, dropna, isnull, interpolate label Jul 15, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Groupby Missing-data np.nan, pd.NaT, pd.NA, dropna, isnull, interpolate
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Ambiguous behaviour when transform groupby with NaNs
3 participants