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 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.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` causing an error to be raised when the input :class:`DataFrame` was subset as a :class:`DataFrame` after groupby (``[['a']]`` and not ``['a']``) and the given callable returned :class:`Series` that were not all indexed the same. (:issue:`52444`)
-

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