Skip to content

BUG: ValueError on groupby with categoricals #35253

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

Merged
merged 5 commits into from
Jul 13, 2020
Merged
Show file tree
Hide file tree
Changes from 3 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/v1.1.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1091,6 +1091,7 @@ Groupby/resample/rolling
- Bug in :meth:`Rolling.apply` where ``center=True`` was ignored when ``engine='numba'`` was specified (:issue:`34784`)
- Bug in :meth:`DataFrame.ewm.cov` was throwing ``AssertionError`` for :class:`MultiIndex` inputs (:issue:`34440`)
- Bug in :meth:`core.groupby.DataFrameGroupBy.transform` when ``func='nunique'`` and columns are of type ``datetime64``, the result would also be of type ``datetime64`` instead of ``int64`` (:issue:`35109`)
- Bug in :meth:'DataFrameGroupBy.first' and :meth:'DataFrameGroupBy.last' that would raise ``ValueError`` grouping on multiple ``Categoricals`` (:issue:`34951`)

Reshaping
^^^^^^^^^
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/groupby/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -1058,7 +1058,7 @@ def _cython_agg_blocks(
# reductions; see GH#28949
obj = obj.iloc[:, 0]

s = get_groupby(obj, self.grouper)
s = get_groupby(obj, self.grouper, observed=True)
try:
result = s.aggregate(lambda x: alt(x, axis=self.axis))
except TypeError:
Expand Down
24 changes: 24 additions & 0 deletions pandas/tests/groupby/test_categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -1669,3 +1669,27 @@ def test_categorical_transform():
expected["status"] = expected["status"].astype(delivery_status_type)

tm.assert_frame_equal(result, expected)


@pytest.mark.parametrize("func", ["first", "last"])
def test_groupby_first_on_categorical_col_grouped_on_2_categoricals(func: str):
# GH 34951

cat = pd.Categorical([0, 0, 1, 1])
val = [0, 1, 1, 0]
df = pd.DataFrame({"a": cat, "b": cat, "c": val})

idx = pd.Categorical([0, 1])
idx = pd.MultiIndex.from_product([idx, idx], names=["a", "b"])
expected = {
"first": pd.Series([0, np.NaN, np.NaN, 1], idx, name="c"),
"last": pd.Series([1, np.NaN, np.NaN, 0], idx, name="c"),
}

df_grp = df.groupby(["a", "b"])
df_res = getattr(df_grp, func)()
tm.assert_frame_equal(df_res, expected[func].to_frame())

srs_grp = df_grp["c"]
srs_res = getattr(srs_grp, func)()
tm.assert_series_equal(srs_res, expected[func])