Skip to content

ENH: Add indexing syntax to GroupBy.nth() #44688

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 20 commits into from
Dec 4, 2021
Merged
Show file tree
Hide file tree
Changes from 11 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
8 changes: 8 additions & 0 deletions doc/source/whatsnew/v1.4.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,14 @@ Previously, negative arguments returned empty frames.
df.groupby("A").nth(slice(1, -1))
df.groupby("A").nth([slice(None, 1), slice(-1, None)])

:meth:`.GroupBy.nth` now accepts index notation.

.. ipython:: python

df.groupby("A").nth[1, -1]
df.groupby("A").nth[1:-1]
df.groupby("A").nth[:1, -1:]

.. _whatsnew_140.dict_tight:

DataFrame.from_dict and DataFrame.to_dict have new ``'tight'`` option
Expand Down
34 changes: 33 additions & 1 deletion pandas/core/groupby/groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,10 @@ class providing the base-class of operations.
numba_,
ops,
)
from pandas.core.groupby.indexing import GroupByIndexingMixin
from pandas.core.groupby.indexing import (
GroupByIndexingMixin,
GroupByNthSelector,
)
from pandas.core.indexes.api import (
CategoricalIndex,
Index,
Expand Down Expand Up @@ -902,6 +905,15 @@ def __getattr__(self, attr: str):
f"'{type(self).__name__}' object has no attribute '{attr}'"
)

def __getattribute__(self, attr):
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 type args & outputs

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Typed the arg, but the output has no type

# Intercept nth to allow both call and index
if attr == "nth":
return GroupByNthSelector(self)
elif attr == "nth_actual":
return super().__getattribute__("nth")
else:
return super().__getattribute__(attr)

@final
def _make_wrapper(self, name: str) -> Callable:
assert name in self._apply_allowlist
Expand Down Expand Up @@ -2524,6 +2536,9 @@ def nth(
"""
Take the nth row from each group if n is an int, otherwise a subset of rows.

Can be either a call or an index. dropna is not available with index notation.
Index notation accepts a comma separated list of integers and slices.

If dropna, will take the nth non-null row, dropna is either
'all' or 'any'; this is equivalent to calling dropna(how=dropna)
before the groupby.
Expand All @@ -2535,6 +2550,7 @@ def nth(

.. versionchanged:: 1.4.0
Added slice and lists containiing slices.
Added index notation.

dropna : {'any', 'all', None}, default None
Apply the specified dropna operation before counting which row is
Expand Down Expand Up @@ -2580,6 +2596,22 @@ def nth(
1 2.0
2 3.0

Index notation may also be used

>>> g.nth[0, 1]
B
A
1 NaN
1 2.0
2 3.0
2 5.0
>>> g.nth[:-1]
B
A
1 NaN
1 2.0
2 3.0

Specifying `dropna` allows count ignoring ``NaN``

>>> g.nth(0, dropna='any')
Expand Down
20 changes: 20 additions & 0 deletions pandas/core/groupby/indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from typing import (
TYPE_CHECKING,
Iterable,
Literal,
cast,
)

Expand Down Expand Up @@ -281,3 +282,22 @@ def __getitem__(self, arg: PositionalIndexer | tuple) -> DataFrame | Series:
self.groupby_object._reset_group_selection()
mask = self.groupby_object._make_mask_from_positional_indexer(arg)
return self.groupby_object._mask_selected_obj(mask)


class GroupByNthSelector:
"""
Dynamically substituted for GroupBy.nth to enable both call and index
"""

def __init__(self, groupby_object: groupby.GroupBy):
self.groupby_object = groupby_object

def __call__(
self,
n: PositionalIndexer | tuple,
dropna: Literal["any", "all", None] = None,
) -> DataFrame | Series:
return self.groupby_object.nth_actual(n, dropna)

def __getitem__(self, n: PositionalIndexer | tuple) -> DataFrame | Series:
return self.groupby_object.nth_actual(n)
9 changes: 9 additions & 0 deletions pandas/tests/groupby/test_nth.py
Original file line number Diff line number Diff line change
Expand Up @@ -726,6 +726,15 @@ def test_slice(slice_test_df, slice_test_grouped, arg, expected_rows):
tm.assert_frame_equal(result, expected)


def test_nth_indexed(slice_test_df, slice_test_grouped):
# Test index notation GH #44688

result = slice_test_grouped.nth[0, 1, -2:]
expected = slice_test_df.iloc[[0, 1, 2, 3, 4, 6, 7]]

tm.assert_frame_equal(result, expected)


def test_invalid_argument(slice_test_grouped):
# Test for error on invalid argument

Expand Down