Skip to content

DEPR: Not passing tuple to get_group when grouping on length-1 list-likes #54155

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 7 commits into from
Aug 21, 2023
Merged
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
2 changes: 1 addition & 1 deletion doc/source/user_guide/cookbook.rst
Original file line number Diff line number Diff line change
Expand Up @@ -466,7 +466,7 @@ Unlike agg, apply's callable is passed a sub-DataFrame which gives you access to

.. ipython:: python

gb = df.groupby(["animal"])
gb = df.groupby("animal")
gb.get_group("cat")

`Apply to different items in a group
Expand Down
4 changes: 2 additions & 2 deletions doc/source/user_guide/groupby.rst
Original file line number Diff line number Diff line change
Expand Up @@ -211,9 +211,9 @@ For example, the groups created by ``groupby()`` below are in the order they app
.. ipython:: python

df3 = pd.DataFrame({"X": ["A", "B", "A", "B"], "Y": [1, 4, 3, 2]})
df3.groupby(["X"]).get_group("A")
df3.groupby("X").get_group("A")

df3.groupby(["X"]).get_group("B")
df3.groupby(["X"]).get_group(("B",))


.. _groupby.dropna:
Expand Down
2 changes: 2 additions & 0 deletions doc/source/whatsnew/v2.2.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,8 @@ Deprecations
- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_markdown` except ``buf``. (:issue:`54229`)
- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_pickle` except ``path``. (:issue:`54229`)
- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_string` except ``buf``. (:issue:`54229`)
- Deprecated not passing a tuple to :class:`DataFrameGroupBy.get_group` or :class:`SeriesGroupBy.get_group` when grouping by a length-1 list-like (:issue:`25971`)

-

.. ---------------------------------------------------------------------------
Expand Down
22 changes: 21 additions & 1 deletion pandas/core/groupby/groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -1033,7 +1033,7 @@ def get_group(self, name, obj=None) -> DataFrame | Series:
owl 1 2 3
toucan 1 5 6
eagle 7 8 9
>>> df.groupby(by=["a"]).get_group(1)
>>> df.groupby(by=["a"]).get_group((1,))
a b c
owl 1 2 3
toucan 1 5 6
Expand All @@ -1053,6 +1053,26 @@ def get_group(self, name, obj=None) -> DataFrame | Series:
2023-01-15 2
dtype: int64
"""
keys = self.keys
level = self.level
# mypy doesn't recognize level/keys as being sized when passed to len
if (is_list_like(level) and len(level) == 1) or ( # type: ignore[arg-type]
is_list_like(keys) and len(keys) == 1 # type: ignore[arg-type]
):
# GH#25971
if isinstance(name, tuple) and len(name) == 1:
# Allow users to pass tuples of length 1 to silence warning
name = name[0]
elif not isinstance(name, tuple):
warnings.warn(
"When grouping with a length-1 list-like, "
"you will need to pass a length-1 tuple to get_group in a future "
"version of pandas. Pass `(name,)` instead of `name` to silence "
"this warning.",
FutureWarning,
stacklevel=find_stack_level(),
)

inds = self._get_index(name)
if not len(inds):
raise KeyError(name)
Expand Down
5 changes: 4 additions & 1 deletion pandas/tests/groupby/test_categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,10 @@ def test_level_get_group(observed):
names=["Index1", "Index2"],
),
)
result = g.get_group("a")
msg = "you will need to pass a length-1 tuple"
with tm.assert_produces_warning(FutureWarning, match=msg):
# GH#25971 - warn when not passing a length-1 tuple
result = g.get_group("a")

tm.assert_frame_equal(result, expected)

Expand Down
28 changes: 28 additions & 0 deletions pandas/tests/groupby/test_groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -3159,3 +3159,31 @@ def test_groupby_series_with_datetimeindex_month_name():
expected = Series([2, 1], name="jan")
expected.index.name = "jan"
tm.assert_series_equal(result, expected)


@pytest.mark.parametrize("test_series", [True, False])
@pytest.mark.parametrize(
"kwarg, value, name, warn",
[
("by", "a", 1, None),
("by", ["a"], 1, FutureWarning),
("by", ["a"], (1,), None),
("level", 0, 1, None),
("level", [0], 1, FutureWarning),
("level", [0], (1,), None),
],
)
def test_depr_get_group_len_1_list_likes(test_series, kwarg, value, name, warn):
# GH#25971
obj = DataFrame({"b": [3, 4, 5]}, index=Index([1, 1, 2], name="a"))
if test_series:
obj = obj["b"]
gb = obj.groupby(**{kwarg: value})
msg = "you will need to pass a length-1 tuple"
with tm.assert_produces_warning(warn, match=msg):
result = gb.get_group(name)
if test_series:
expected = Series([3, 4], index=Index([1, 1], name="a"), name="b")
else:
expected = DataFrame({"b": [3, 4]}, index=Index([1, 1], name="a"))
tm.assert_equal(result, expected)
4 changes: 1 addition & 3 deletions pandas/tests/reshape/merge/test_join.py
Original file line number Diff line number Diff line change
Expand Up @@ -813,9 +813,7 @@ def _check_join(left, right, result, join_col, how="left", lsuffix="_x", rsuffix
left_grouped = left.groupby(join_col)
right_grouped = right.groupby(join_col)

for group_key, group in result.groupby(
join_col if len(join_col) > 1 else join_col[0]
):
for group_key, group in result.groupby(join_col):
l_joined = _restrict_to_columns(group, left.columns, lsuffix)
r_joined = _restrict_to_columns(group, right.columns, rsuffix)

Expand Down