Skip to content

PERF: groupby.transform skip fast path when only a single group exists #45820

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 2 commits into from
Feb 4, 2022
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/v1.5.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,7 @@ Performance improvements
- Performance improvement in :meth:`.GroupBy.transform` for some user-defined DataFrame -> Series functions (:issue:`45387`)
- Performance improvement in :meth:`DataFrame.duplicated` when subset consists of only one column (:issue:`45236`)
- Performance improvement in :meth:`.GroupBy.transform` when broadcasting values for user-defined functions (:issue:`45708`)
- Performance improvement in :meth:`.GroupBy.transform` for user-defined functions when only a single group exists (:issue:`44977`)
-

.. ---------------------------------------------------------------------------
Expand Down
5 changes: 5 additions & 0 deletions pandas/core/groupby/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -1208,6 +1208,11 @@ def _choose_path(self, fast_path: Callable, slow_path: Callable, group: DataFram
path = slow_path
res = slow_path(group)

if self.ngroups == 1:
# no need to evaluate multiple paths when only
# a single group exists
return path, res

# if we make it here, test if we can use the fast path
try:
res_fast = fast_path(group)
Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/groupby/transform/test_transform.py
Original file line number Diff line number Diff line change
Expand Up @@ -480,7 +480,7 @@ def test_transform_coercion():
# 14457
# when we are transforming be sure to not coerce
# via assignment
df = DataFrame({"A": ["a", "a"], "B": [0, 1]})
df = DataFrame({"A": ["a", "a", "b", "b"], "B": [0, 1, 3, 4]})
g = df.groupby("A")

expected = g.transform(np.mean)
Expand Down