Skip to content

BUG: groupby.agg doesn't include grouping columns in result when selected #51398

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 6 commits into from
Feb 24, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v2.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1362,7 +1362,7 @@ Groupby/resample/rolling
- Bug in :meth:`.DataFrameGroupBy.describe` produced incorrect results when data had duplicate columns (:issue:`50806`)
- Bug in :meth:`.DataFrameGroupBy.agg` with ``engine="numba"`` failing to respect ``as_index=False`` (:issue:`51228`)
- Bug in :meth:`DataFrameGroupBy.agg`, :meth:`SeriesGroupBy.agg`, and :meth:`Resampler.agg` would ignore arguments when passed a list of functions (:issue:`50863`)
-
- Bug in :meth:`DataFrameGroupBy.agg` with multiple groupings would not include groupings in the result when they occurred in the selected columns (:issue:`51186`)
Copy link
Member

Choose a reason for hiding this comment

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

with multiple groupings

this might not be clear without looking at the new test

Copy link
Member Author

Choose a reason for hiding this comment

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

Yea, I wasn't sure how to describe that the bug only occurs with .groupby([x, y]) and not .groupby(x). Is there better language that could be used here, or maybe just remove it altogether?

Copy link
Member

Choose a reason for hiding this comment

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

'after subsetting columns (e.g. gb[["a", "b"]].agg(...)'?


Reshaping
^^^^^^^^^
Expand Down
10 changes: 2 additions & 8 deletions pandas/core/groupby/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -1320,21 +1320,15 @@ def aggregate(self, func=None, *args, engine=None, engine_kwargs=None, **kwargs)
agg = aggregate

def _iterate_slices(self) -> Iterable[Series]:
obj = self._selected_obj
obj = self._obj_with_exclusions
if self.axis == 1:
obj = obj.T

if isinstance(obj, Series) and obj.name not in self.exclusions:
if isinstance(obj, Series):
# Occurs when doing DataFrameGroupBy(...)["X"]
yield obj
else:
for label, values in obj.items():
if label in self.exclusions:
# Note: if we tried to just iterate over _obj_with_exclusions,
# we would break test_wrap_agg_out by yielding a column
# that is skipped here but not dropped from obj_with_exclusions
continue

yield values

def _aggregate_frame(self, func, *args, **kwargs) -> DataFrame:
Expand Down
18 changes: 16 additions & 2 deletions pandas/tests/groupby/aggregate/test_aggregate.py
Original file line number Diff line number Diff line change
Expand Up @@ -321,8 +321,9 @@ def func(ser):

with pytest.raises(TypeError, match="Test error message"):
grouped.aggregate(func)
result = grouped[[c for c in three_group if c != "C"]].aggregate(func)
exp_grouped = three_group.loc[:, three_group.columns != "C"]
columns = ["D", "E", "F"]
result = grouped[columns].aggregate(func)
exp_grouped = three_group.loc[:, columns]
expected = exp_grouped.groupby(["A", "B"]).aggregate(func)
tm.assert_frame_equal(result, expected)

Expand Down Expand Up @@ -1515,3 +1516,16 @@ def foo2(x, b=2, c=0):
[[8, 8], [9, 9], [10, 10]], index=Index([1, 2, 3]), columns=["foo1", "foo2"]
)
tm.assert_frame_equal(result, expected)


def test_agg_groupings_selection():
# GH#51186 - a selected grouping should be in the output of agg
df = DataFrame({"a": [1, 1, 2], "b": [3, 3, 4], "c": [5, 6, 7]})
gb = df.groupby(["a", "b"])
selected_gb = gb[["b", "c"]]
result = selected_gb.agg(lambda x: x.sum())
index = MultiIndex(
levels=[[1, 2], [3, 4]], codes=[[0, 1], [0, 1]], names=["a", "b"]
)
expected = DataFrame({"b": [6, 4], "c": [11, 7]}, index=index)
tm.assert_frame_equal(result, expected)