Skip to content

BUG: Fix inconsistent GroupBy.aggregate behavior with as_index=False when grouping by external Series with conflicting names #58337 #58774

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

Closed
Closed
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
22 changes: 22 additions & 0 deletions pandas/core/groupby/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -1577,6 +1577,28 @@ def aggregate(self, func=None, *args, engine=None, engine_kwargs=None, **kwargs)
if not self.as_index:
result = self._insert_inaxis_grouper(result)
result.index = default_index(len(result))
group_keys = []

if isinstance(self.keys, Series): # Ensure consistent namespace usage
group_keys.append(self.keys.name)
if self.keys.name not in result.columns:
result.insert(0, self.keys.name, self.keys)
else:
group_keys.extend(key for key in self.keys if key in self.obj.columns)

if not result.index.equals(default_index(len(result))):
result.reset_index(drop=False, inplace=True)

if group_keys:
for key in group_keys:
if key not in result.columns:
result.insert(0, key, self.obj[key])

if not self.as_index and isinstance(
self.keys, Series
): # Ensure consistent namespace usage
# Remove any duplicate entries for series key
result = result.loc[:, ~result.columns.duplicated()]

return result

Expand Down
31 changes: 31 additions & 0 deletions pandas/tests/groupby/test_groupby_aggregate_as_index.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import pytest

import pandas as pd
import pandas.testing as pdt


@pytest.fixture
def sample_df():
return pd.DataFrame(
{
"A": ["foo", "bar", "foo", "bar", "foo", "bar", "foo", "foo"],
"B": ["one", "one", "two", "three", "two", "two", "one", "three"],
"C": [1, 2, 3, 4, 5, 6, 7, 8],
"D": [2.0, 5.0, 8.0, 1.0, 2.0, 9.0, 7.0, 8.0],
}
)


def test_groupby_aggregate_as_index_false_with_column_key(sample_df):
grouped = sample_df.groupby("A", as_index=False)
result = grouped.aggregate({"C": "sum"})
expected = pd.DataFrame({"A": ["bar", "foo"], "C": [12, 24]})
pdt.assert_frame_equal(result, expected)


def test_groupby_aggregate_as_index_false_with_no_grouping_keys(sample_df):
grouped = sample_df.groupby("A", as_index=False)
result = grouped.aggregate({"D": "sum"})
expected = pd.DataFrame({"A": ["bar", "foo"], "D": [15.0, 27.0]})
pdt.assert_frame_equal(result, expected)
assert result.index.equals(pd.RangeIndex(start=0, stop=len(result), step=1))
Loading