Skip to content

BUG: error when unstacking in DataFrameGroupby.apply #52446

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
Show file tree
Hide file tree
Changes from 2 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.1.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,7 @@ Groupby/resample/rolling
or :class:`PeriodIndex`, and the ``groupby`` method was given a function as its first argument,
the function operated on the whole index rather than each element of the index. (:issue:`51979`)
- Bug in :meth:`GroupBy.var` failing to raise ``TypeError`` when called with datetime64 or :class:`PeriodDtype` values (:issue:`52128`)
- Bug in :meth:`DataFrameGroupBy.apply` when the supplied callable unstacked the grouped :class:`DataFrame` and returned a :class:`Series`, an attempt was made to set a list as the name of the result ``Series``, causing an error to be raised (:issue:`52444`)
Copy link
Member

@rhshadrach rhshadrach Apr 5, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this bug occurs a bit more generally - anytime the input DataFrame is subset as a DataFrame after groupby ([['a']] and not ['a']) and the UDF returns Series that aren't all indexed the same.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I’ve reformulated.

-

Reshaping
Expand Down
8 changes: 7 additions & 1 deletion pandas/core/groupby/groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -1192,7 +1192,13 @@ def _concat_objects(
else:
result = concat(values, axis=self.axis)

name = self.obj.name if self.obj.ndim == 1 else self._selection
if self.obj.ndim == 1:
name = self.obj.name
elif is_hashable(self._selection):
name = self._selection
else:
name = None

if isinstance(result, Series) and name is not None:
result.name = name

Expand Down
20 changes: 20 additions & 0 deletions pandas/tests/groupby/test_apply.py
Original file line number Diff line number Diff line change
Expand Up @@ -1203,6 +1203,26 @@ def test_groupby_apply_shape_cache_safety():
tm.assert_frame_equal(result, expected)


def test_groupby_apply_to_series_name():
# GH52444
df = DataFrame.from_dict(
{
"a": ["a", "b", "a", "b"],
"b1": ["aa", "ac", "ac", "ad"],
"b2": ["aa", "aa", "aa", "ac"],
}
)
grp = df.groupby("a")[["b1", "b2"]]
result = grp.apply(lambda x: x.unstack().value_counts())

expected_idx = MultiIndex.from_arrays(
arrays=[["a", "a", "b", "b", "b"], ["aa", "ac", "ac", "ad", "aa"]],
names=["a", None],
)
expected = Series([3, 1, 2, 1, 1], index=expected_idx, name="count")
tm.assert_series_equal(result, expected)


@pytest.mark.parametrize("dropna", [True, False])
def test_apply_na(dropna):
# GH#28984
Expand Down