Skip to content

Commit acc330a

Browse files
committed
PERF: fix #32976 slow group by for categorical columns
Aggregate categorical codes with fast cython aggregation for select `how` operations.
1 parent 3ae33c6 commit acc330a

File tree

4 files changed

+74
-3
lines changed

4 files changed

+74
-3
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,), (int, str), ("last", "head", "count")]
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

+2-1
Original file line numberDiff line numberDiff line change
@@ -323,7 +323,7 @@ Other API changes
323323
- ``loc`` lookups with an object-dtype :class:`Index` and an integer key will now raise ``KeyError`` instead of ``TypeError`` when key is missing (:issue:`31905`)
324324
- Using a :func:`pandas.api.indexers.BaseIndexer` with ``count``, ``min``, ``max``, ``median``, ``skew``, ``cov``, ``corr`` will now return correct results for any monotonic :func:`pandas.api.indexers.BaseIndexer` descendant (:issue:`32865`)
325325
- Added a :func:`pandas.api.indexers.FixedForwardWindowIndexer` class to support forward-looking windows during ``rolling`` operations.
326-
-
326+
- :meth:`DataFrame.groupby` aggregations of categorical series will now return a :class:`Categorical` while preserving the codes and categories of the original series
327327

328328
Backwards incompatible API changes
329329
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -624,6 +624,7 @@ Performance improvements
624624
- Performance improvement in reductions (sum, prod, min, max) for nullable (integer and boolean) dtypes (:issue:`30982`, :issue:`33261`, :issue:`33442`).
625625
- Performance improvement in arithmetic operations between two :class:`DataFrame` objects (:issue:`32779`)
626626
- Performance improvement in :class:`pandas.core.groupby.RollingGroupby` (:issue:`34052`)
627+
- Performance improvement in :meth:`DataFrame.groupby` when aggregating categorical data (:issue:`32976`)
627628

628629
.. ---------------------------------------------------------------------------
629630

pandas/core/groupby/ops.py

+42-1
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@
4040
from pandas.core.dtypes.missing import _maybe_fill, isna
4141

4242
import pandas.core.algorithms as algorithms
43+
from pandas.core.arrays.categorical import Categorical
4344
from pandas.core.base import SelectionMixin
4445
import pandas.core.common as com
4546
from pandas.core.frame import DataFrame
@@ -355,6 +356,29 @@ def get_group_levels(self) -> List[Index]:
355356

356357
_name_functions = {"ohlc": ["open", "high", "low", "close"]}
357358

359+
_cat_method_blacklist = (
360+
"add",
361+
"median",
362+
"prod",
363+
"sem",
364+
"cumsum",
365+
"sum",
366+
"cummin",
367+
"mean",
368+
"max",
369+
"skew",
370+
"cumprod",
371+
"cummax",
372+
"rank",
373+
"pct_change",
374+
"min",
375+
"var",
376+
"mad",
377+
"describe",
378+
"std",
379+
"quantile",
380+
)
381+
358382
def _is_builtin_func(self, arg):
359383
"""
360384
if we define a builtin function for this argument, return it,
@@ -459,7 +483,7 @@ def _cython_operation(
459483

460484
# categoricals are only 1d, so we
461485
# are not setup for dim transforming
462-
if is_categorical_dtype(values.dtype) or is_sparse(values.dtype):
486+
if is_sparse(values.dtype):
463487
raise NotImplementedError(f"{values.dtype} dtype not supported")
464488
elif is_datetime64_any_dtype(values.dtype):
465489
if how in ["add", "prod", "cumsum", "cumprod"]:
@@ -480,6 +504,7 @@ def _cython_operation(
480504

481505
is_datetimelike = needs_i8_conversion(values.dtype)
482506
is_numeric = is_numeric_dtype(values.dtype)
507+
is_categorical = is_categorical_dtype(values)
483508

484509
if is_datetimelike:
485510
values = values.view("int64")
@@ -495,6 +520,17 @@ def _cython_operation(
495520
values = ensure_int_or_float(values)
496521
elif is_numeric and not is_complex_dtype(values):
497522
values = ensure_float64(values)
523+
elif is_categorical:
524+
if how in self._cat_method_blacklist:
525+
raise NotImplementedError(
526+
f"{values.dtype} dtype not supported for `how` argument {how}"
527+
)
528+
values, categories, ordered = (
529+
values.codes.astype(np.int64),
530+
values.categories,
531+
values.ordered,
532+
)
533+
is_numeric = True
498534
else:
499535
values = values.astype(object)
500536

@@ -571,6 +607,11 @@ def _cython_operation(
571607
result = type(orig_values)(result.astype(np.int64), dtype=orig_values.dtype)
572608
elif is_datetimelike and kind == "aggregate":
573609
result = result.astype(orig_values.dtype)
610+
elif is_categorical:
611+
# re-create categories
612+
result = Categorical.from_codes(
613+
result, categories=categories, ordered=ordered,
614+
)
574615

575616
if is_extension_array_dtype(orig_values.dtype):
576617
result = maybe_cast_result(result=result, obj=orig_values, how=how)

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)