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 9 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 @@ -815,6 +815,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 scalar 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
13 changes: 13 additions & 0 deletions pandas/core/groupby/groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ class providing the base-class of operations.
cache_readonly,
doc,
)
from pandas.util._exceptions import find_stack_level

from pandas.core.dtypes.cast import ensure_dtype_can_hold_na
from pandas.core.dtypes.common import (
Expand Down Expand Up @@ -626,6 +627,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,7 +812,18 @@ 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(level, list) and len(level) == 1:
# GH 51583
warnings.warn(
"Initializing a Groupby object with a length-1 list "
"level parameter will yield indexes as tuples in a future version. "
"To keep indexes as scalars, initialize Groupby objects with "
"a scalar level parameter instead.",
FutureWarning,
stacklevel=find_stack_level(),
)
if isinstance(keys, list) and len(keys) == 1:
# GH#42795 - when keys is a list, return tuples even when length is 1
result = (((key,), group) for key, group in result)
Expand Down
26 changes: 26 additions & 0 deletions pandas/tests/groupby/test_groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -2709,6 +2709,32 @@ def test_single_element_list_grouping():
assert result == expected


def test_single_element_list_level_grouping_deprecation():
# GH 51583
depr_msg = (
"Initializing a Groupby object with a length-1 list "
"level parameter will yield indexes as tuples in a future version. "
"To keep indexes as scalars, initialize Groupby objects with "
"a scalar level parameter instead."
)
with tm.assert_produces_warning(FutureWarning, match=depr_msg):
df = DataFrame({"a": [1, 2], "b": [3, 4], "c": [5, 6]}, index=["x", "y"])
[key for key, _ in df.groupby(level=[0])]


def test_multiindex_single_element_list_level_grouping_deprecation():
# GH 51583
depr_msg = (
"Initializing a Groupby object with a length-1 list "
"level parameter will yield indexes as tuples in a future version. "
"To keep indexes as scalars, initialize Groupby objects with "
"a scalar level parameter instead."
)
with tm.assert_produces_warning(FutureWarning, match=depr_msg):
df = MultiIndex.from_product([[1, 2], [3, 4]], names=["x", "y"]).to_frame()
[key for key, _ in df.groupby(level=[0])]


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