Skip to content

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

Merged
merged 17 commits into from
May 5, 2019
Merged
Show file tree
Hide file tree
Changes from 6 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 doc/source/whatsnew/v0.25.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -389,6 +389,7 @@ Groupby/Resample/Rolling
- Ensured that result group order is correct when grouping on an ordered ``Categorical`` and specifying ``observed=True`` (:issue:`25871`, :issue:`25167`)
- Bug in :meth:`pandas.core.window.Rolling.min` and :meth:`pandas.core.window.Rolling.max` that caused a memory leak (:issue:`25893`)
- Bug in :func:`idxmax` and :func:`idxmin` on :meth:`DataFrame.groupby` with datetime column would return incorrect dtype (:issue:`25444`, :issue:`15306`)
- Bug in :meth:`pandas.core.groupby.GroupBy.nth` where NA values in the grouping would return incorrect results (:issue:`26011`)

Reshaping
^^^^^^^^^
Expand Down
10 changes: 7 additions & 3 deletions pandas/core/groupby/groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -1546,7 +1546,9 @@ 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[Union[bool, str]] = None) -> DataFrame:
Copy link
Contributor

Choose a reason for hiding this comment

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

Options[str] here

"""
Take the nth row from each group if n is an int, or a subset of rows
if n is a list of ints.
Expand Down Expand Up @@ -1636,11 +1638,13 @@ def nth(self, n, dropna=None):
-nth_values)
mask = mask_left | mask_right

ids, _, _ = self.grouper.group_info
mask = mask & (ids != -1) # Drop NA values in grouping
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 put the comment on the prior line


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
Expand Down
17 changes: 17 additions & 0 deletions pandas/tests/groupby/test_nth.py
Original file line number Diff line number Diff line change
Expand Up @@ -434,3 +434,20 @@ def test_nth_column_order():
columns=['C', 'B'],
index=Index([1, 2], name='A'))
assert_frame_equal(result, expected)


@pytest.mark.parametrize("dropna", [None, 'any', 'all'])
def test_nth_nan_in_grouper(dropna):
# GH 26011
df = DataFrame([
[np.nan, 0, 1],
['abc', 2, 3],
[np.nan, 4, 5],
['def', 6, 7],
[np.nan, 8, 9],
], columns=list('abc'))
result = df.groupby('a').nth(0, dropna=dropna)
expected = pd.DataFrame([[2, 3], [6, 7]], columns=list('bc'),
index=Index(['abc', 'def'], name='a'))

assert_frame_equal(result, expected)