{"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/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/apply.py#L785-L821","documentation":"Raised by `normalize_dictlike_arg` when, on a DataFrame, the keys of the dict-like func reference column labels that do not exist in `obj.columns`. Pandas computes the set difference and reports the missing labels so the user fixes the spec rather than getting a silently truncated result. Tracked via GH 58474.","triggerScenarios":"`df.agg({'nonexistent_col': 'mean'})`, `df.transform({'typo_col': 'shift'})`, or any dict-spec whose keys include labels not in `df.columns`. Fires only when `obj.ndim != 1` (DataFrame path).","commonSituations":"Typos in column names, case mismatches ('Name' vs 'name'), trailing whitespace in column headers from CSV ingestion, or referencing columns after they were dropped/renamed earlier in the pipeline.","solutions":["Print `df.columns.tolist()` and compare against the dict keys to find the typo/mismatch.","Strip/normalize column names right after reading data: `df.columns = df.columns.str.strip()`.","Intersect keys with columns before calling: `spec = {k: v for k, v in spec.items() if k in df.columns}` (and warn on dropped keys)."],"exampleFix":"// before\ndf.agg({'Total': 'sum'})  # but column is 'total'\n// after\ndf.agg({'total': 'sum'})","handlingStrategy":"validation","validationCode":"def validate_agg_columns(df, spec):\n    missing = [k for k in spec.keys() if k not in df.columns]\n    if missing:\n        raise KeyError(f'agg spec references missing columns: {missing}. ' f'Available: {list(df.columns)}')\n    return spec","typeGuard":"def spec_keys_in_columns(spec, df) -> bool:\n    cols = set(df.columns)\n    return all(k in cols for k in spec.keys())","tryCatchPattern":"try:\n    out = df.agg(spec)\nexcept KeyError as e:\n    if 'do not exist' in str(e):\n        valid = {k: v for k, v in spec.items() if k in df.columns}\n        out = df.agg(valid)\n    else:\n        raise","preventionTips":["Strip/normalize column names right after read_csv.","Validate spec keys against df.columns before calling agg.","Use frozenset(df.columns) lookups to catch typos cheaply."],"tags":["pandas","agg","missing-column","keyerror","validation"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}