Skip to content

Commit 9fbb860

Browse files
authored
BUG: Removed bug from groupby/min on categoricals (#52236)
* removed bug WrappedCythonOp * added test * added functions to test
1 parent 32f789f commit 9fbb860

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

pandas/core/groupby/ops.py

+2
Original file line numberDiff line numberDiff line change
@@ -402,6 +402,8 @@ def _ea_wrap_cython_operation(
402402

403403
if self.how in self.cast_blocklist:
404404
return res_values
405+
elif self.how in ["first", "last", "min", "max"]:
406+
res_values[result_mask == 1] = -1
405407
return values._from_backing_data(res_values)
406408

407409
npvalues = self._ea_to_cython_values(values)

pandas/tests/groupby/test_min_max.py

+23
Original file line numberDiff line numberDiff line change
@@ -247,3 +247,26 @@ def test_min_max_nullable_uint64_empty_group():
247247
res = gb.max()
248248
expected.iloc[0, 0] = 9
249249
tm.assert_frame_equal(res, expected)
250+
251+
252+
@pytest.mark.parametrize("func", ["first", "last", "min", "max"])
253+
def test_groupby_min_max_categorical(func):
254+
# GH: 52151
255+
df = DataFrame(
256+
{
257+
"col1": pd.Categorical(["A"], categories=list("AB"), ordered=True),
258+
"col2": pd.Categorical([1], categories=[1, 2], ordered=True),
259+
"value": 0.1,
260+
}
261+
)
262+
result = getattr(df.groupby("col1", observed=False), func)()
263+
264+
idx = pd.CategoricalIndex(data=["A", "B"], name="col1", ordered=True)
265+
expected = DataFrame(
266+
{
267+
"col2": pd.Categorical([1, None], categories=[1, 2], ordered=True),
268+
"value": [0.1, None],
269+
},
270+
index=idx,
271+
)
272+
tm.assert_frame_equal(result, expected)

0 commit comments

Comments
 (0)