From a6943ae49f79452da6ca5f1c3e008ded4e0e2c85 Mon Sep 17 00:00:00 2001 From: Shoham Debnath Date: Wed, 1 Sep 2021 05:28:06 +0530 Subject: [PATCH] TST: groupby.first/last retains categorical dtype (#43153) --- pandas/tests/groupby/test_categorical.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/pandas/tests/groupby/test_categorical.py b/pandas/tests/groupby/test_categorical.py index 63ae54cafc900..d989cde09380a 100644 --- a/pandas/tests/groupby/test_categorical.py +++ b/pandas/tests/groupby/test_categorical.py @@ -1741,3 +1741,15 @@ def test_groupby_categorical_indices_unused_categories(): assert result.keys() == expected.keys() for key in result.keys(): tm.assert_numpy_array_equal(result[key], expected[key]) + + +@pytest.mark.parametrize("func", ["first", "last"]) +def test_groupby_last_first_preserve_categoricaldtype(func): + # GH#33090 + df = DataFrame({"a": [1, 2, 3]}) + df["b"] = df["a"].astype("category") + result = getattr(df.groupby("a")["b"], func)() + expected = Series( + Categorical([1, 2, 3]), name="b", index=Index([1, 2, 3], name="a") + ) + tm.assert_series_equal(expected, result)