{"record":{"id":"1523009fbd0aa686","repo":"pandas-dev/pandas","slug":"columns-not-found-str-bad-keys-1-1","errorCode":null,"errorMessage":"Columns not found: {str(bad_keys)[1:-1]}","messagePattern":"Columns not found: (.+?)","errorType":"exception","errorClass":"KeyError","httpStatus":null,"severity":"error","filePath":"pandas/core/base.py","lineNumber":219,"sourceCode":"        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\n        Parameters\n        ----------\n        key : str / list of selections\n        ndim : {1, 2}\n            requested ndim of result","sourceCodeStart":201,"sourceCodeEnd":237,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/base.py#L201-L237","documentation":"Raised by SelectionMixin.__getitem__ (the bracket selector on groupby/rolling/expanding/resample window objects) when a list/tuple/Series/Index/ndarray of column names is passed and at least one name does not exist in the underlying DataFrame's columns. The bad keys are computed as set(key).difference(self.obj.columns) and rendered without the surrounding list brackets. It exists so column selection on grouped/windowed data fails fast with the offending names instead of producing empty groups.","triggerScenarios":"Calling df.groupby('a')[['a','missing']] or rolling/expanding/resample objects indexed with a list where any label is absent, e.g. grouped[['b','typo']]. Also triggered by passing an np.ndarray or Index of labels containing a misspelled/dropped column, or after a rename/drop that left stale names in user code.","commonSituations":"Renaming columns (df.rename) or dropping them after copy-pasting a selection list; typos in column names; case mismatches ('Name' vs 'name'); trailing/leading whitespace introduced by reading CSVs; code written against an older schema.","solutions":["Inspect df.columns and correct the list to only contain existing labels.","Intersect before selecting: cols = [c for c in wanted if c in df.columns]; grouped[cols].","Normalize names on read: df = pd.read_csv(...).rename(columns=lambda c: c.strip()).","Guard with set difference: missing = set(wanted) - set(df.columns); assert not missing, missing."],"exampleFix":"// before\ngrouped = df.groupby('id')[['id', 'amout']]\n// after\nwanted = ['id', 'amount']\nmissing = set(wanted) - set(df.columns)\nassert not missing, f'missing cols: {missing}'\ngrouped = df.groupby('id')[wanted]","handlingStrategy":"validation","validationCode":"wanted = ['a', 'b', 'c']\nmissing = set(wanted) - set(df.columns)\nif missing:\n    raise KeyError(f'columns not in df: {missing}')\ngrouped = df.groupby('id')[wanted]","typeGuard":"def safe_columns(df, wanted):\n    cols = list(wanted) if not isinstance(wanted, str) else [wanted]\n    missing = [c for c in cols if c not in df.columns]\n    if missing:\n        raise KeyError(missing)\n    return cols","tryCatchPattern":null,"preventionTips":["Validate column lists against df.columns before passing to groupby/rolling selection.","Strip CSV headers at load time to avoid whitespace mismatches.","Keep a single source of truth (e.g. constants module) for column names."],"tags":["key-error","column-selection","groupby","indexing","schema-mismatch"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}