{"record":{"id":"67de9bfdd97f3d7b","repo":"pandas-dev/pandas","slug":"label-s-list-cols-do-not-exist","errorCode":null,"errorMessage":"Label(s) {list(cols)} do not exist","messagePattern":"Label\\(s\\) (.+?) do not exist","errorType":"exception","errorClass":"KeyError","httpStatus":null,"severity":"error","filePath":"pandas/core/apply.py","lineNumber":803,"sourceCode":"        assert how in (\"apply\", \"agg\", \"transform\")\n\n        # Can't use func.values(); wouldn't work for a Series\n        if (\n            how == \"agg\"\n            and isinstance(obj, ABCSeries)\n            and any(is_list_like(v) for _, v in func.items())\n        ) or (any(is_dict_like(v) for _, v in func.items())):\n            # GH 15931 - deprecation of renaming keys\n            raise SpecificationError(\"nested renamer is not supported\")\n\n        if obj.ndim != 1:\n            # Check for missing columns on a frame\n            from pandas import Index\n\n            cols = Index(list(func.keys())).difference(obj.columns, sort=True)\n            if len(cols) > 0:\n                # GH 58474\n                raise KeyError(f\"Label(s) {list(cols)} do not exist\")\n\n        aggregator_types = (list, tuple, dict)\n\n        # if we have a dict of any non-scalars\n        # eg. {'A' : ['mean']}, normalize all to\n        # be list-likes\n        # Cannot use func.values() because arg may be a Series\n        if any(isinstance(x, aggregator_types) for _, x in func.items()):\n            new_func: AggFuncTypeDict = {}\n            for k, v in func.items():\n                if not isinstance(v, aggregator_types):\n                    new_func[k] = [v]\n                else:\n                    new_func[k] = v\n            func = new_func\n        return func\n\n    def _apply_str(self, obj, func: str, *args, **kwargs):","sourceCodeStart":785,"sourceCodeEnd":821,"githubUrl":"https://github.com/pandas-dev/pandas/blob/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/apply.py#L785-L821","documentation":"Raised in `normalize_dictlike_arg` when a dict-like function spec references column labels that do not exist in the DataFrame's columns. The check computes the set difference between the dict keys and `obj.columns`; any missing labels are reported. Added/strengthened in GH#58474 to fail fast rather than silently producing NaN results.","triggerScenarios":"`df.agg({'nonexistent_col': 'mean'})` on a DataFrame lacking that column. Also dynamic dict construction where a key is misspelled or refers to a column dropped earlier in the pipeline.","commonSituations":"Typos in column names; refactoring where columns are renamed/dropped but agg specs are not updated; building the dict from an external schema that drifted from the data.","solutions":["Verify the dict keys against `df.columns` before calling: `missing = set(func_dict) - set(df.columns)`.","Use `Intersection`/filtering: `{k: v for k, v in func_dict.items() if k in df.columns}`.","Fix the typo or restore the missing column upstream in the pipeline."],"exampleFix":"# before\ndf.agg({'total': 'sum'})  # column is actually 'totals'\n# after\ndf.agg({'totals': 'sum'})\n# or guard dynamically\nops = {k: v for k, v in ops.items() if k in df.columns}","handlingStrategy":"validation","validationCode":"def safe_agg(df, spec):\n    missing = set(spec) - set(df.columns)\n    if missing:\n        raise KeyError(f'columns not in df: {missing}')\n    return df.agg(spec)","typeGuard":"def spec_keys_in_columns(spec, df) -> bool:\n    return set(spec).issubset(set(df.columns))","tryCatchPattern":"try:\n    df.agg(spec)\nexcept KeyError as e:\n    # filter spec to existing columns and retry, or surface a clear error\n    valid = {k: v for k, v in spec.items() if k in df.columns}\n    df.agg(valid)","preventionTips":["Validate dict keys against df.columns before calling agg.","Build agg specs from df.columns itself rather than external schemas that may drift."],"tags":["pandas","agg","apply","keyerror","missing-column","validation"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}