diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 25f2b76054712..1b3046f955786 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -882,11 +882,11 @@ def get_group(self, name) -> DataFrame | Series: if isinstance(name, tuple) and len(name) == 1: name = name[0] else: - raise KeyError(name) + raise KeyError(f"Group {name} not found") inds = self._get_index(name) if not len(inds): - raise KeyError(name) + raise KeyError(f"Group {name} not found") return self._selected_obj.iloc[inds] @final diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py index 54716bfff0fba..493254298934f 100644 --- a/pandas/tests/groupby/test_groupby.py +++ b/pandas/tests/groupby/test_groupby.py @@ -2887,6 +2887,13 @@ def test_get_group_len_1_list_likes(test_series, kwarg, value, name, warn): tm.assert_equal(result, expected) +def test_get_group_missing_group_error_message(): + df = DataFrame({"a": [1, 2], "b": [3, 4]}) + + with pytest.raises(KeyError, match="Group 3 not found"): + df.groupby("a").get_group(3) + + def test_groupby_ngroup_with_nan(): # GH#50100 df = DataFrame({"a": Categorical([np.nan]), "b": [1]})