-
-
Notifications
You must be signed in to change notification settings - Fork 18.5k
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 17 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 |
---|---|---|
|
@@ -82,32 +82,40 @@ did not have the same index as the input. | |
|
||
.. code-block:: ipython | ||
|
||
In [3]: df.groupby('a', dropna=True).transform('sum') | ||
Out[3]: | ||
b | ||
0 5 | ||
1 5 | ||
2 5 | ||
|
||
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') | ||
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. add a comment here on the casting of the fill value 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. I think you're saying to explain why the old result comes out as |
||
Out[3]: | ||
b | ||
0 2 | ||
1 3 | ||
2 -9223372036854775808 | ||
|
||
In [3]: df.groupby('a', dropna=True).transform(lambda x: x) | ||
Out[3]: | ||
b | ||
0 2 | ||
1 3 | ||
|
||
In [3]: df.groupby('a', dropna=True).transform('sum') | ||
Out[3]: | ||
b | ||
0 5 | ||
1 5 | ||
2 5 | ||
|
||
*New behavior*: | ||
|
||
.. ipython:: python | ||
|
||
df.groupby('a', dropna=True).transform('sum') | ||
df.groupby('a', dropna=True).transform(lambda x: x.sum()) | ||
df.groupby('a', dropna=True).transform('ffill') | ||
df.groupby('a', dropna=True).transform(lambda x: x) | ||
df.groupby('a', dropna=True).transform('sum') | ||
|
||
.. _whatsnew_150.notable_bug_fixes.notable_bug_fix2: | ||
|
||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -62,6 +62,7 @@ class providing the base-class of operations. | |
) | ||
from pandas.util._exceptions import find_stack_level | ||
|
||
from pandas.core.dtypes.cast import ensure_dtype_can_hold_na | ||
from pandas.core.dtypes.common import ( | ||
is_bool_dtype, | ||
is_datetime64_dtype, | ||
|
@@ -950,7 +951,18 @@ def curried(x): | |
if name in base.plotting_methods: | ||
return self.apply(curried) | ||
|
||
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: | ||
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.
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. 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. |
||
# apply sets the name on each group as the key; if there is one | ||
# group this name will come through on Series results | ||
result.name = None | ||
|
||
if self.grouper.has_dropped_na and name in base.transformation_kernels: | ||
# result will have dropped rows due to nans, fill with null | ||
# and ensure index is ordered same as the input | ||
result = self._set_result_index_ordered(result) | ||
return result | ||
|
||
wrapper.__name__ = name | ||
return wrapper | ||
|
@@ -2608,7 +2620,11 @@ def blk_func(values: ArrayLike) -> ArrayLike: | |
# then there will be no -1s in indexer, so we can use | ||
# the original dtype (no need to ensure_dtype_can_hold_na) | ||
if isinstance(values, np.ndarray): | ||
out = np.empty(values.shape, dtype=values.dtype) | ||
dtype = values.dtype | ||
if self.grouper.has_dropped_na: | ||
# dropped null groups give rise to nan in the result | ||
dtype = ensure_dtype_can_hold_na(values.dtype) | ||
out = np.empty(values.shape, dtype=dtype) | ||
else: | ||
out = type(values)._empty(values.shape, dtype=values.dtype) | ||
|
||
|
@@ -3114,9 +3130,13 @@ def ngroup(self, ascending: bool = True): | |
""" | ||
with self._group_selection_context(): | ||
index = self._selected_obj.index | ||
result = self._obj_1d_constructor( | ||
self.grouper.group_info[0], index, dtype=np.int64 | ||
) | ||
comp_ids = self.grouper.group_info[0] | ||
if self.grouper.has_dropped_na: | ||
comp_ids = np.where(comp_ids == -1, np.nan, comp_ids) | ||
dtype = np.float64 | ||
else: | ||
dtype = np.int64 | ||
result = self._obj_1d_constructor(comp_ids, index, dtype=dtype) | ||
if not ascending: | ||
result = self.ngroups - 1 - result | ||
return result | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -37,6 +37,7 @@ | |
from pandas.util._decorators import cache_readonly | ||
|
||
from pandas.core.dtypes.cast import ( | ||
ensure_dtype_can_hold_na, | ||
maybe_cast_pointwise_result, | ||
maybe_downcast_to_dtype, | ||
) | ||
|
@@ -104,7 +105,8 @@ class WrappedCythonOp: | |
# back to the original dtype. | ||
cast_blocklist = frozenset(["rank", "count", "size", "idxmin", "idxmax"]) | ||
|
||
def __init__(self, kind: str, how: str): | ||
def __init__(self, grouper: BaseGrouper, kind: str, how: str): | ||
self.grouper = grouper | ||
self.kind = kind | ||
self.how = how | ||
|
||
|
@@ -194,7 +196,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.grouper.has_dropped_na | ||
): | ||
# result may still include NaN, so we have to cast | ||
values = ensure_float64(values) | ||
|
||
|
@@ -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) | ||
|
||
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. 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) 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. It seems better to me to determine the result dtype upfront, rather than cast after, as much as possible. 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. 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. 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. Makes sense - I didn't realize that my change to |
||
if how == "rank": | ||
out_dtype = "float64" | ||
else: | ||
|
@@ -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 | ||
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 this be rolled into the mask-reshaping done above? 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 block turned out to not be necessary. It will be removed. |
||
mask = mask[None, :] | ||
|
||
return self._call_cython_op( | ||
values, | ||
min_count=min_count, | ||
|
@@ -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 | ||
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 | ||
|
@@ -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) | ||
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. @jbrockmendel - It would suffice to pass 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. I'd much rather just has_dropped_na be part of WrappedCythonOop's state |
||
|
||
ids, _, _ = self.group_info | ||
ngroups = self.ngroups | ||
|
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])