Skip to content
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

PERF: groupby(...).__len__ #57595

Merged
merged 2 commits into from
Feb 24, 2024
Merged
Show file tree
Hide file tree
Changes from all 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/v3.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,7 @@ Performance improvements
- Performance improvement in :meth:`RangeIndex.take` returning a :class:`RangeIndex` instead of a :class:`Index` when possible. (:issue:`57445`)
- Performance improvement in indexing operations for string dtypes (:issue:`56997`)
- :meth:`Series.str.extract` returns a :class:`RangeIndex` columns instead of an :class:`Index` column when possible (:issue:`?``)
- Performance improvement in ``DataFrameGroupBy.__len__`` and ``SeriesGroupBy.__len__`` (:issue:`57595`)

.. ---------------------------------------------------------------------------
.. _whatsnew_300.bug_fixes:
Expand Down
2 changes: 1 addition & 1 deletion pandas/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,7 @@ def axis(request):
return request.param


@pytest.fixture(params=[True, False, None])
@pytest.fixture(params=[True, False])
Copy link
Member Author

Choose a reason for hiding this comment

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

Stumbled into this because of the added test. This should have been removed by #57330

def observed(request):
"""
Pass in the observed keyword to groupby for [True, False]
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/groupby/groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -596,7 +596,7 @@ class BaseGroupBy(PandasObject, SelectionMixin[NDFrameT], GroupByIndexingMixin):

@final
def __len__(self) -> int:
return len(self.groups)
return self._grouper.ngroups

@final
def __repr__(self) -> str:
Expand Down
23 changes: 23 additions & 0 deletions pandas/tests/groupby/test_groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,29 @@ def test_len_nan_group():
assert len(df.groupby(["a", "b"])) == 0


@pytest.mark.parametrize("keys", [["a"], ["a", "b"]])
def test_len_categorical(dropna, observed, keys):
# GH#57595
df = DataFrame(
{
"a": Categorical([1, 1, 2, np.nan], categories=[1, 2, 3]),
"b": Categorical([1, 1, 2, np.nan], categories=[1, 2, 3]),
"c": 1,
}
)
gb = df.groupby(keys, observed=observed, dropna=dropna)
result = len(gb)
if observed and dropna:
expected = 2
elif observed and not dropna:
expected = 3
elif len(keys) == 1:
expected = 3 if dropna else 4
else:
expected = 9 if dropna else 16
assert result == expected, f"{result} vs {expected}"


def test_basic_regression():
# regression
result = Series([1.0 * x for x in list(range(1, 10)) * 10])
Expand Down
Loading