-
-
Notifications
You must be signed in to change notification settings - Fork 18.4k
Fix Bug with NA value in Grouping for Groupby.nth #26152
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 14 commits
e62a14f
e113b55
823225b
068936f
8716764
3000d2b
84ddd6d
84d343a
6f40fbe
e2d006d
69014a7
0b7eb6c
48d90ee
7eea5e3
4dec450
ce0abcd
c2a0b8e
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 |
---|---|---|
|
@@ -12,7 +12,7 @@ class providing the base-class of operations. | |
import datetime | ||
from functools import partial, wraps | ||
import types | ||
from typing import FrozenSet, Optional, Tuple, Type | ||
from typing import FrozenSet, List, Optional, Tuple, Type, Union | ||
import warnings | ||
|
||
import numpy as np | ||
|
@@ -1546,15 +1546,16 @@ def backfill(self, limit=None): | |
|
||
@Substitution(name='groupby') | ||
@Substitution(see_also=_common_see_also) | ||
def nth(self, n, dropna=None): | ||
def nth(self, | ||
n: Union[int, List[int]], | ||
dropna: Optional[str] = None) -> DataFrame: | ||
""" | ||
Take the nth row from each group if n is an int, or a subset of rows | ||
if n is a list of ints. | ||
|
||
If dropna, will take the nth non-null row, dropna is either | ||
Truthy (if a Series) or 'all', 'any' (if a DataFrame); | ||
this is equivalent to calling dropna(how=dropna) before the | ||
groupby. | ||
'all' or 'any'; this is equivalent to calling dropna(how=dropna) | ||
before the groupby. | ||
|
||
Parameters | ||
---------- | ||
|
@@ -1617,92 +1618,102 @@ def nth(self, n, dropna=None): | |
4 2 5.0 | ||
""" | ||
|
||
if isinstance(n, int): | ||
nth_values = [n] | ||
elif isinstance(n, (set, list, tuple)): | ||
nth_values = list(set(n)) | ||
if dropna is not None: | ||
raise ValueError( | ||
"dropna option with a list of nth values is not supported") | ||
else: | ||
valid_containers = (set, list, tuple) | ||
if not isinstance(n, (valid_containers, int)): | ||
raise TypeError("n needs to be an int or a list/set/tuple of ints") | ||
|
||
nth_values = np.array(nth_values, dtype=np.intp) | ||
self._set_group_selection() | ||
|
||
if not dropna: | ||
mask_left = np.in1d(self._cumcount_array(), nth_values) | ||
|
||
if isinstance(n, int): | ||
nth_values = [n] | ||
elif isinstance(n, valid_containers): | ||
nth_values = list(set(n)) | ||
|
||
nth_array = np.array(nth_values, dtype=np.intp) | ||
self._set_group_selection() | ||
|
||
mask_left = np.in1d(self._cumcount_array(), nth_array) | ||
mask_right = np.in1d(self._cumcount_array(ascending=False) + 1, | ||
-nth_values) | ||
-nth_array) | ||
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. Note I had to change this because |
||
mask = mask_left | mask_right | ||
|
||
ids, _, _ = self.grouper.group_info | ||
|
||
# Drop NA values in grouping | ||
mask = mask & (ids != -1) | ||
|
||
out = self._selected_obj[mask] | ||
if not self.as_index: | ||
return out | ||
|
||
ids, _, _ = self.grouper.group_info | ||
out.index = self.grouper.result_index[ids[mask]] | ||
|
||
return out.sort_index() if self.sort else out | ||
|
||
if dropna not in ['any', 'all']: | ||
if isinstance(self._selected_obj, Series) and dropna is True: | ||
warnings.warn("the dropna={dropna} keyword is deprecated," | ||
"use dropna='all' instead. " | ||
"For a Series groupby, dropna must be " | ||
"either None, 'any' or 'all'.".format( | ||
dropna=dropna), | ||
FutureWarning, | ||
stacklevel=2) | ||
dropna = 'all' | ||
else: | ||
# Note: when agg-ing picker doesn't raise this, | ||
# just returns NaN | ||
raise ValueError("For a DataFrame groupby, dropna must be " | ||
"either None, 'any' or 'all', " | ||
"(was passed {dropna}).".format( | ||
dropna=dropna)) | ||
|
||
# old behaviour, but with all and any support for DataFrames. | ||
# modified in GH 7559 to have better perf | ||
max_len = n if n >= 0 else - 1 - n | ||
dropped = self.obj.dropna(how=dropna, axis=self.axis) | ||
|
||
# get a new grouper for our dropped obj | ||
if self.keys is None and self.level is None: | ||
|
||
# we don't have the grouper info available | ||
# (e.g. we have selected out | ||
# a column that is not in the current object) | ||
axis = self.grouper.axis | ||
grouper = axis[axis.isin(dropped.index)] | ||
|
||
else: | ||
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 de-dent this here and remove the else which is unecessary; add a comment though of what this branch is |
||
if isinstance(n, valid_containers): | ||
raise ValueError( | ||
"dropna option with a list of nth values is not supported") | ||
|
||
# create a grouper with the original parameters, but on the dropped | ||
# object | ||
from pandas.core.groupby.grouper import _get_grouper | ||
grouper, _, _ = _get_grouper(dropped, key=self.keys, | ||
axis=self.axis, level=self.level, | ||
sort=self.sort, | ||
mutated=self.mutated) | ||
|
||
grb = dropped.groupby(grouper, as_index=self.as_index, sort=self.sort) | ||
sizes, result = grb.size(), grb.nth(n) | ||
mask = (sizes < max_len).values | ||
|
||
# set the results which don't meet the criteria | ||
if len(result) and mask.any(): | ||
result.loc[mask] = np.nan | ||
|
||
# reset/reindex to the original groups | ||
if (len(self.obj) == len(dropped) or | ||
len(result) == len(self.grouper.result_index)): | ||
result.index = self.grouper.result_index | ||
else: | ||
result = result.reindex(self.grouper.result_index) | ||
if dropna not in ['any', 'all']: | ||
if isinstance(self._selected_obj, Series) and dropna is True: | ||
warnings.warn("the dropna={dropna} keyword is deprecated," | ||
"use dropna='all' instead. " | ||
"For a Series groupby, dropna must be " | ||
"either None, 'any' or 'all'.".format( | ||
dropna=dropna), | ||
FutureWarning, | ||
stacklevel=2) | ||
dropna = 'all' | ||
else: | ||
# Note: when agg-ing picker doesn't raise this, | ||
# just returns NaN | ||
raise ValueError("For a DataFrame groupby, dropna must be " | ||
"either None, 'any' or 'all', " | ||
"(was passed {dropna}).".format( | ||
dropna=dropna)) | ||
|
||
# old behaviour, but with all and any support for DataFrames. | ||
# modified in GH 7559 to have better perf | ||
max_len = n if n >= 0 else - 1 - n | ||
dropped = self.obj.dropna(how=dropna, axis=self.axis) | ||
|
||
# get a new grouper for our dropped obj | ||
if self.keys is None and self.level is None: | ||
|
||
# we don't have the grouper info available | ||
# (e.g. we have selected out | ||
# a column that is not in the current object) | ||
axis = self.grouper.axis | ||
grouper = axis[axis.isin(dropped.index)] | ||
|
||
return result | ||
else: | ||
|
||
# create a grouper with the original parameters, but on dropped | ||
# object | ||
from pandas.core.groupby.grouper import _get_grouper | ||
grouper, _, _ = _get_grouper(dropped, key=self.keys, | ||
axis=self.axis, level=self.level, | ||
sort=self.sort, | ||
mutated=self.mutated) | ||
|
||
grb = dropped.groupby( | ||
grouper, as_index=self.as_index, sort=self.sort) | ||
sizes, result = grb.size(), grb.nth(n) | ||
mask = (sizes < max_len).values | ||
|
||
# set the results which don't meet the criteria | ||
if len(result) and mask.any(): | ||
result.loc[mask] = np.nan | ||
|
||
# reset/reindex to the original groups | ||
if (len(self.obj) == len(dropped) or | ||
len(result) == len(self.grouper.result_index)): | ||
result.index = self.grouper.result_index | ||
else: | ||
result = result.reindex(self.grouper.result_index) | ||
|
||
return result | ||
|
||
def quantile(self, q=0.5, interpolation='linear'): | ||
""" | ||
|
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.
Instead of explicitly checking
if dropna is not None
this condition was refactored to sit in a branch that follows the implicit condition ofif dropna
.There is however a slight behavior difference between this PR and master, where now these are equivalent:
Whereas on master these would not yield the same thing:
I think the new behavior is more consistent and preferred. Might be worth a whatsnew