{"record":{"id":"93cfa4d6d21fd84f","repo":"pandas-dev/pandas","slug":"column-s-self-selection-already-selected","errorCode":null,"errorMessage":"Column(s) {self._selection} already selected","messagePattern":"Column\\(s\\) (.+?) already selected","errorType":"exception","errorClass":"IndexError","httpStatus":null,"severity":"error","filePath":"pandas/core/base.py","lineNumber":214,"sourceCode":"        return self._selected_obj.ndim\n\n    @final\n    @cache_readonly\n    def _obj_with_exclusions(self):\n        if isinstance(self.obj, ABCSeries):\n            return self.obj\n\n        if self._selection is not None:\n            return self.obj[self._selection_list]\n\n        if len(self.exclusions) > 0:\n            return self.obj._drop_axis(self.exclusions, axis=1)\n        else:\n            return self.obj\n\n    def __getitem__(self, key):\n        if self._selection is not None:\n            raise IndexError(f\"Column(s) {self._selection} already selected\")\n\n        if isinstance(key, (list, tuple, ABCSeries, ABCIndex, np.ndarray)):\n            if len(self.obj.columns.intersection(key)) != len(set(key)):\n                bad_keys = list(set(key).difference(self.obj.columns))\n                raise KeyError(f\"Columns not found: {str(bad_keys)[1:-1]}\")\n            return self._gotitem(list(key), ndim=2)\n\n        else:\n            if key not in self.obj:\n                raise KeyError(f\"Column not found: {key}\")\n            ndim = self.obj[key].ndim\n            return self._gotitem(key, ndim=ndim)\n\n    def _gotitem(self, key, ndim: int, subset=None):\n        \"\"\"\n        sub-classes to define\n        return a sliced object\n","sourceCodeStart":196,"sourceCodeEnd":232,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/base.py#L196-L232","documentation":"Raised by SelectionMixin.__getitem__ when a selection has already been made on the group-like object (its `_selection` is not None) and the caller tries to index into it again. Because the object already represents a fixed column subset, further column selection is ambiguous and is rejected as IndexError, directing the user to restructure the selection.","triggerScenarios":"Calling `g['col']` (or a list/tuple/Series/Index/array key) on a groupby/rolling/resampler selection object that was already created with a column selection, e.g. `df.groupby('a')['b']['c']`.","commonSituations":"Chaining selection operations on groupby/rolling objects; code refactors that combine a column selection with a later `.getitem` call.","solutions":["Make the column selection once, at the groupby/rolling construction site, instead of chaining.","Recreate the groupby/rolling object from the original DataFrame if a different column subset is needed.","Access the underlying object via `.obj` and re-select from there."],"exampleFix":"# before\ng = df.groupby('a')['b']\ng['c']  # IndexError: Column(s) b already selected\n\n# after\ng = df.groupby('a')[['b', 'c']]","handlingStrategy":"validation","validationCode":"def can_select_again(selection_obj) -> bool:\n    # SelectionMixin objects whose _selection is set will reject further indexing\n    return getattr(selection_obj, '_selection', None) is None","typeGuard":"def selection_already_made(selection_obj) -> bool:\n    return getattr(selection_obj, '_selection', None) is not None","tryCatchPattern":"try:\n    sub = group_selection[key]\nexcept IndexError as e:\n    if 'already selected' in str(e):\n        sub = group_selection.obj[key]  # re-select from the underlying object\n    else:\n        raise","preventionTips":["Make column selections once, at groupby/rolling construction, rather than chaining.","If you need a different subset, recreate the groupby/rolling from the original DataFrame.","Access the underlying object via .obj to re-select when needed."],"tags":["selection","groupby","index","indexerror","selectionmixin"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}