Skip to content

BUG: Consistent result ordering for groupbys with categorical groupings #49318

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

Closed
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/v2.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,7 @@ Categorical
^^^^^^^^^^^
- Bug in :meth:`Categorical.set_categories` losing dtype information (:issue:`48812`)
- Bug in :meth:`DataFrame.groupby` and :meth:`Series.groupby` would reorder categories when used as a grouper (:issue:`48749`)
- Bug in :class:`GroupBy` when a categorical column was used as a grouper with a range index, ordering of the result would depend on the `sort` argument but if the index was categorical it would depend on the `order` attribute of the index (:issue:`49223`)

Datetimelike
^^^^^^^^^^^^
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/groupby/categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def recode_for_groupby(
unique_codes = unique1d(c.codes)

take_codes = unique_codes[unique_codes != -1]
if c.ordered:
if sort:
take_codes = np.sort(take_codes)

# we recode according to the uniques
Expand Down
13 changes: 13 additions & 0 deletions pandas/core/groupby/grouper.py
Original file line number Diff line number Diff line change
Expand Up @@ -502,6 +502,17 @@ def __init__(
self._group_index,
) = index._get_grouper_for_level(mapper, level=ilevel, dropna=dropna)

if is_categorical_dtype(self.grouping_vector):
self.grouping_vector: Categorical

self._passed_categorical = True
self._orig_cats = self.grouping_vector.categories

# Should the sort arg be just `sort` or `sort or self.grouping_vector.ordered`?
self.grouping_vector, self._all_grouper = recode_for_groupby(
self.grouping_vector, sort, observed
)

# a passed Grouper like, directly get the grouper in the same way
# as single grouper groupby, use the group_info to get codes
elif isinstance(self.grouping_vector, Grouper):
Expand Down Expand Up @@ -529,6 +540,8 @@ def __init__(
self._passed_categorical = True

self._orig_cats = self.grouping_vector.categories

# Should the sort arg be just `sort` or `sort or self.grouping_vector.ordered`?
self.grouping_vector, self._all_grouper = recode_for_groupby(
self.grouping_vector, sort, observed
)
Expand Down
31 changes: 31 additions & 0 deletions pandas/tests/groupby/test_categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -2046,3 +2046,34 @@ def test_many_categories(as_index, sort, index_kind, ordered):
expected = DataFrame({"a": Series(index), "b": data})

tm.assert_frame_equal(result, expected)


def test_categorical_vs_range_index_sorting():
categories = np.arange(4, -1, -1)
for range_index in [True, False]:
df_ordered = DataFrame(
{
"a": Categorical([2, 1, 2, 3], categories=categories, ordered=True),
"b": range(4),
}
)
df_unordered = DataFrame(
{
"a": Categorical([2, 1, 2, 3], categories=categories, ordered=False),
"b": range(4),
}
)

if not range_index:
df_ordered = df_ordered.set_index("a")
df_unordered = df_unordered.set_index("a")

gb_ordered_sort = df_ordered.groupby("a", sort=True, observed=True)
gb_ordered_nosort = df_ordered.groupby("a", sort=False, observed=True)
gb_unordered_sort = df_unordered.groupby("a", sort=True, observed=True)
gb_unordered_nosort = df_unordered.groupby("a", sort=False, observed=True)

assert gb_ordered_sort.sum()["b"].tolist() == [3, 2, 1]
assert gb_ordered_nosort.sum()["b"].tolist() == [2, 1, 3]
assert gb_unordered_sort.sum()["b"].tolist() == [3, 2, 1]
assert gb_unordered_nosort.sum()["b"].tolist() == [2, 1, 3]