Skip to content

Commit 357845d

Browse files
authored
PERF: groupby.transform skip fast path when only a single group exists (#45820)
1 parent 899a6bf commit 357845d

File tree

3 files changed

+7
-1
lines changed

3 files changed

+7
-1
lines changed

doc/source/whatsnew/v1.5.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,7 @@ Performance improvements
205205
- Performance improvement in :meth:`.GroupBy.transform` for some user-defined DataFrame -> Series functions (:issue:`45387`)
206206
- Performance improvement in :meth:`DataFrame.duplicated` when subset consists of only one column (:issue:`45236`)
207207
- Performance improvement in :meth:`.GroupBy.transform` when broadcasting values for user-defined functions (:issue:`45708`)
208+
- Performance improvement in :meth:`.GroupBy.transform` for user-defined functions when only a single group exists (:issue:`44977`)
208209
-
209210

210211
.. ---------------------------------------------------------------------------

pandas/core/groupby/generic.py

+5
Original file line numberDiff line numberDiff line change
@@ -1208,6 +1208,11 @@ def _choose_path(self, fast_path: Callable, slow_path: Callable, group: DataFram
12081208
path = slow_path
12091209
res = slow_path(group)
12101210

1211+
if self.ngroups == 1:
1212+
# no need to evaluate multiple paths when only
1213+
# a single group exists
1214+
return path, res
1215+
12111216
# if we make it here, test if we can use the fast path
12121217
try:
12131218
res_fast = fast_path(group)

pandas/tests/groupby/transform/test_transform.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -480,7 +480,7 @@ def test_transform_coercion():
480480
# 14457
481481
# when we are transforming be sure to not coerce
482482
# via assignment
483-
df = DataFrame({"A": ["a", "a"], "B": [0, 1]})
483+
df = DataFrame({"A": ["a", "a", "b", "b"], "B": [0, 1, 3, 4]})
484484
g = df.groupby("A")
485485

486486
expected = g.transform(np.mean)

0 commit comments

Comments
 (0)