Skip to content

Commit a16f6a2

Browse files
committed
PERF: fix pandas-dev#32976 slow group by for categorical columns
Aggregate categorical codes with fast cython aggregation for select `how` operations.
1 parent 22cf0f5 commit a16f6a2

File tree

4 files changed

+72
-2
lines changed

4 files changed

+72
-2
lines changed

asv_bench/benchmarks/groupby.py

+29
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
from pandas import (
88
Categorical,
9+
CategoricalDtype,
910
DataFrame,
1011
MultiIndex,
1112
Series,
@@ -473,6 +474,7 @@ def time_sum(self):
473474

474475

475476
class Categories:
477+
# benchmark grouping by categoricals
476478
def setup(self):
477479
N = 10 ** 5
478480
arr = np.random.random(N)
@@ -510,6 +512,33 @@ def time_groupby_extra_cat_nosort(self):
510512
self.df_extra_cat.groupby("a", sort=False)["b"].count()
511513

512514

515+
class CategoricalFrame:
516+
# benchmark grouping with operations on categorical values (GH #32976)
517+
param_names = ["groupby_type", "value_type", "agg_method"]
518+
params = [(int, str), (int, str), ('last', 'mean', 'head')]
519+
520+
def setup(self, groupby_type, value_type, agg_method):
521+
SIZE = 100000
522+
GROUPS = 1000
523+
CARDINALITY = 10
524+
CAT = CategoricalDtype([value_type(i) for i in range(CARDINALITY)])
525+
df = DataFrame(
526+
{
527+
"group": [
528+
groupby_type(np.random.randint(0, GROUPS)) for i in range(SIZE)
529+
],
530+
"cat": [np.random.choice(CAT.categories) for i in range(SIZE)],
531+
}
532+
)
533+
self.df_cat_values = df.astype({"cat": CAT})
534+
535+
def time_groupby(self, groupby_type, value_type, agg_method):
536+
getattr(self.df_cat_values.groupby("group"), agg_method)()
537+
538+
def time_groupby_ordered(self, groupby_type, value_type, agg_method):
539+
getattr(self.df_cat_values.groupby("group", sort=True), agg_method)()
540+
541+
513542
class Datelike:
514543
# GH 14338
515544
params = ["period_range", "date_range", "date_range_tz"]

doc/source/whatsnew/v1.1.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -461,6 +461,7 @@ Performance improvements
461461
:meth:`DataFrame.sparse.from_spmatrix` constructor (:issue:`32821`,
462462
:issue:`32825`, :issue:`32826`, :issue:`32856`, :issue:`32858`).
463463
- Performance improvement in reductions (sum, prod, min, max) for nullable (integer and boolean) dtypes (:issue:`30982`, :issue:`33261`, :issue:`33442`).
464+
- Performance improvement in :meth:`DataFrame.groupby` when aggregating categorical data (:issue:`32976`)
464465

465466

466467
.. ---------------------------------------------------------------------------

pandas/core/groupby/ops.py

+41-1
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@
3939
from pandas.core.dtypes.missing import _maybe_fill, isna
4040

4141
import pandas.core.algorithms as algorithms
42+
from pandas.core.arrays.categorical import Categorical
4243
from pandas.core.base import SelectionMixin
4344
import pandas.core.common as com
4445
from pandas.core.frame import DataFrame
@@ -459,7 +460,7 @@ def _cython_operation(
459460

460461
# categoricals are only 1d, so we
461462
# are not setup for dim transforming
462-
if is_categorical_dtype(values) or is_sparse(values):
463+
if is_sparse(values):
463464
raise NotImplementedError(f"{values.dtype} dtype not supported")
464465
elif is_datetime64_any_dtype(values):
465466
if how in ["add", "prod", "cumsum", "cumprod"]:
@@ -480,6 +481,29 @@ def _cython_operation(
480481

481482
is_datetimelike = needs_i8_conversion(values.dtype)
482483
is_numeric = is_numeric_dtype(values.dtype)
484+
is_categorical = is_categorical_dtype(values)
485+
cat_method_blacklist = (
486+
"add",
487+
"median",
488+
"prod",
489+
"sem",
490+
"cumsum",
491+
"sum",
492+
"cummin",
493+
"mean",
494+
"max",
495+
"skew",
496+
"cumprod",
497+
"cummax",
498+
"rank",
499+
"pct_change",
500+
"min",
501+
"var",
502+
"mad",
503+
"describe",
504+
"std",
505+
"quantile",
506+
)
483507

484508
if is_datetimelike:
485509
values = values.view("int64")
@@ -495,6 +519,17 @@ def _cython_operation(
495519
values = ensure_int_or_float(values)
496520
elif is_numeric and not is_complex_dtype(values):
497521
values = ensure_float64(values)
522+
elif is_categorical:
523+
if how in cat_method_blacklist:
524+
raise NotImplementedError(
525+
f"{values.dtype} dtype not supported for `how` argument {how}"
526+
)
527+
values, categories, ordered = (
528+
values.codes.astype(np.int64),
529+
values.categories,
530+
values.ordered,
531+
)
532+
is_numeric = True
498533
else:
499534
values = values.astype(object)
500535

@@ -582,6 +617,11 @@ def _cython_operation(
582617
result = type(orig_values)(result.astype(np.int64), dtype=orig_values.dtype)
583618
elif is_datetimelike and kind == "aggregate":
584619
result = result.astype(orig_values.dtype)
620+
elif is_categorical:
621+
# re-create categories
622+
result = Categorical.from_codes(
623+
result, categories=categories, ordered=ordered,
624+
)
585625

586626
return result, names
587627

pandas/tests/groupby/aggregate/test_aggregate.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -466,7 +466,7 @@ def test_agg_cython_category_not_implemented_fallback():
466466
result = df.groupby("col_num").col_cat.first()
467467
expected = pd.Series(
468468
[1, 2, 3], index=pd.Index([1, 2, 3], name="col_num"), name="col_cat"
469-
)
469+
).astype("category")
470470
tm.assert_series_equal(result, expected)
471471

472472
result = df.groupby("col_num").agg({"col_cat": "first"})

0 commit comments

Comments
 (0)