Skip to content

BUG: Fix droped result column in groupby with as_index False #33247

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
Show file tree
Hide file tree
Changes from 10 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
38 changes: 38 additions & 0 deletions doc/source/whatsnew/v1.1.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -715,6 +715,43 @@ apply and applymap on ``DataFrame`` evaluates first row/column only once
df.apply(func, axis=1)


.. _whatsnew_110.api_breaking.groupby_results_los_as_index_false:

:meth:`DataFrameGroupby.agg` lost results with ``as_index`` ``False`` when relabeling columns
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Previously :meth:`DataFrameGroupby.agg` lost the result columns, when the ``as_index`` option was
set to ``False`` and the result columns were relabeled. In this case he result values were replaced with
the previous index (:issue:`32240`).

.. ipython:: python

df = pd.DataFrame({"key": ["x", "y", "z", "x", "y", "z"],
"val": [1.0, 0.8, 2.0, 3.0, 3.6, 0.75]})
df

*Previous behavior*:

.. code-block:: ipython

In [2]: grouped = df.groupby("key", as_index=False)
In [3]: result = grouped.agg(min_val=pd.NamedAgg(column="val", aggfunc="min"))
In [4]: result
Out[4]:
min_val
0 x
1 y
2 z

*New behavior*:

.. ipython:: python

grouped = df.groupby("key", as_index=False)
result = grouped.agg(min_val=pd.NamedAgg(column="val", aggfunc="min"))
result


.. _whatsnew_110.deprecations:

Deprecations
Expand Down Expand Up @@ -992,6 +1029,7 @@ Groupby/resample/rolling
The behaviour now is consistent, independent of internal heuristics. (:issue:`31612`, :issue:`14927`, :issue:`13056`)
- Bug in :meth:`SeriesGroupBy.agg` where any column name was accepted in the named aggregation of ``SeriesGroupBy`` previously. The behaviour now allows only ``str`` and callables else would raise ``TypeError``. (:issue:`34422`)
- Bug in :meth:`DataFrame.groupby` lost index, when one of the ``agg`` keys referenced an empty list (:issue:`32580`)
- Bug in :meth:`DataFrameGroupby.agg` lost results, when ``as_index`` option was set to ``False`` and the result columns were relabeled. The result values were replaced with the index values (:issue:`32240`).

Reshaping
^^^^^^^^^
Expand Down
8 changes: 4 additions & 4 deletions pandas/core/groupby/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -980,16 +980,16 @@ def aggregate(
[self._selected_obj.columns.name] * result.columns.nlevels
).droplevel(-1)

if not self.as_index:
self._insert_inaxis_grouper_inplace(result)
result.index = np.arange(len(result))

if relabeling:

# used reordered index of columns
result = result.iloc[:, order]
result.columns = columns

if not self.as_index:
self._insert_inaxis_grouper_inplace(result)
result.index = np.arange(len(result))

return result._convert(datetime=True)

agg = aggregate
Expand Down
35 changes: 35 additions & 0 deletions pandas/tests/groupby/aggregate/test_aggregate.py
Original file line number Diff line number Diff line change
Expand Up @@ -753,6 +753,41 @@ def test_groupby_aggregate_empty_key_empty_return():
tm.assert_frame_equal(result, expected)


def test_grouby_agg_loses_results_with_as_index_false_relabel():
# GH 32240: When the aggregate function relabels column names and
# as_index=False is specified, the results are dropped.

df = pd.DataFrame(
{"key": ["x", "y", "z", "x", "y", "z"], "val": [1.0, 0.8, 2.0, 3.0, 3.6, 0.75]}
)

grouped = df.groupby("key", as_index=False)
result = grouped.agg(min_val=pd.NamedAgg(column="val", aggfunc="min"))
expected = pd.DataFrame({"key": ["x", "y", "z"], "min_val": [1.0, 0.8, 0.75]})
tm.assert_frame_equal(result, expected)


def test_grouby_agg_loses_results_with_as_index_false_relabel_multiindex():
# GH 32240: When the aggregate function relabels column names and
# as_index=False is specified, the results are dropped. Check if
# multiindex is returned in the right order

df = pd.DataFrame(
{
"key": ["x", "y", "x", "y", "x", "x"],
"key1": ["a", "b", "c", "b", "a", "c"],
"val": [1.0, 0.8, 2.0, 3.0, 3.6, 0.75],
}
)

grouped = df.groupby(["key", "key1"], as_index=False)
result = grouped.agg(min_val=pd.NamedAgg(column="val", aggfunc="min"))
expected = pd.DataFrame(
{"key": ["x", "x", "y"], "key1": ["a", "c", "b"], "min_val": [1.0, 0.75, 0.8]}
)
tm.assert_frame_equal(result, expected)


@pytest.mark.parametrize(
"func", [lambda s: s.mean(), lambda s: np.mean(s), lambda s: np.nanmean(s)]
)
Expand Down