Skip to content

DEPR: scalar index for length-1-list level groupby #51817

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 5 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.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -816,6 +816,7 @@ Deprecations
- Deprecated :meth:`DataFrame.pad` in favor of :meth:`DataFrame.ffill` (:issue:`33396`)
- Deprecated :meth:`DataFrame.backfill` in favor of :meth:`DataFrame.bfill` (:issue:`33396`)
- Deprecated :meth:`~pandas.io.stata.StataReader.close`. Use :class:`~pandas.io.stata.StataReader` as a context manager instead (:issue:`49228`)
- Deprecated producing a single element when iterating over a :class:`DataFrameGroupBy` or a :class:`SeriesGroupBy` that has been grouped by a ``level`` parameter that is a list of length 1; A tuple of length one will be returned instead (:issue:`51583`)

.. ---------------------------------------------------------------------------
.. _whatsnew_200.prior_deprecations:
Expand Down
10 changes: 9 additions & 1 deletion pandas/core/groupby/groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -626,6 +626,7 @@ class BaseGroupBy(PandasObject, SelectionMixin[NDFrameT], GroupByIndexingMixin):
axis: AxisInt
grouper: ops.BaseGrouper
keys: _KeysArgType | None = None
level: IndexLabel | None = None
group_keys: bool | lib.NoDefault

@final
Expand Down Expand Up @@ -810,9 +811,16 @@ def __iter__(self) -> Iterator[tuple[Hashable, NDFrameT]]:
for each group
"""
keys = self.keys
level = self.level
result = self.grouper.get_iterator(self._selected_obj, axis=self.axis)
if isinstance(keys, list) and len(keys) == 1:
if (
isinstance(keys, list)
and len(keys) == 1
or isinstance(level, list)
and len(level) == 1
):
# GH#42795 - when keys is a list, return tuples even when length is 1
# GH#51583 - when level is a list, return tuples even when length is 1
result = (((key,), group) for key, group in result)
return result

Expand Down
16 changes: 16 additions & 0 deletions pandas/tests/groupby/test_groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -2709,6 +2709,22 @@ def test_single_element_list_grouping():
assert result == expected


def test_single_element_list_level_grouping():
# GH 51583
df = DataFrame({"a": [1, 2], "b": [3, 4], "c": [5, 6]}, index=["x", "y"])
result = [key for key, _ in df.groupby(level=[0])]
expected = [("x",), ("y",)]
assert result == expected


def test_single_element_list_multiindex_level_grouping():
# GH 51583
df = MultiIndex.from_product([[1, 2], [3, 4]], names=["x", "y"]).to_frame()
result = [key for key, _ in df.groupby(level=[0])]
expected = [(1,), (2,)]
assert result == expected


@pytest.mark.parametrize("func", ["sum", "cumsum", "cumprod", "prod"])
def test_groupby_avoid_casting_to_float(func):
# GH#37493
Expand Down