{"record":{"id":"fabf0e368ee4ac68","repo":"pola-rs/polars","slug":"dimensions-of-columns-arg-len-columns-must-ma","errorCode":null,"errorMessage":"dimensions of columns arg ({len(columns)}) must match data dimensions ({len(data)})","messagePattern":"dimensions of columns arg \\((.+?)\\) must match data dimensions \\((.+?)\\)","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"py-polars/src/polars/_utils/construction/dataframe.py","lineNumber":272,"sourceCode":"        column_dtypes.update(schema_overrides)\n\n    return column_names, column_dtypes\n\n\ndef _handle_columns_arg(\n    data: list[PySeries],\n    columns: Sequence[str] | None = None,\n    *,\n    from_dict: bool = False,\n) -> list[PySeries]:\n    \"\"\"Rename data according to columns argument.\"\"\"\n    if columns is None:\n        return data\n    elif not data:\n        return [pl.Series(name=c)._s for c in columns]\n    elif len(data) != len(columns):\n        msg = f\"dimensions of columns arg ({len(columns)}) must match data dimensions ({len(data)})\"\n        raise ValueError(msg)\n\n    if from_dict:\n        series_map = {s.name(): s for s in data}\n        if all((col in series_map) for col in columns):\n            return [series_map[col] for col in columns]\n\n    for i, c in enumerate(columns):\n        if c != data[i].name():\n            data[i] = data[i].clone()\n            data[i].rename(c)\n\n    return data\n\n\ndef _post_apply_columns(\n    pydf: PyDataFrame,\n    columns: SchemaDefinition | None,\n    structs: dict[str, Struct] | None = None,","sourceCodeStart":254,"sourceCodeEnd":290,"githubUrl":"https://github.com/pola-rs/polars/blob/df599052daf96e7a9cc30a3b0c6bd25d6947e3c0/py-polars/src/polars/_utils/construction/dataframe.py#L254-L290","documentation":"_post_apply_columns renames already-constructed Series according to a `columns` argument after DataFrame assembly. If the number of supplied names differs from the number of Series in the data, this ValueError fires — the list/sequence counterpart of the schema-length checks, also guarding internal paths used after dict construction (from_dict reordering).","triggerScenarios":"Constructing a DataFrame from a sequence of Series or prepared column data together with a `columns` name list of different length, e.g. three series with `columns=[\"a\", \"b\"]`; any internal caller whose name list drifted from the data it passes.","commonSituations":"Reusable loader functions accepting both data and a name list where the data width varies between runs; concatenation/ETL helpers passing along a stale name list after a schema change.","solutions":["Match the counts: pass exactly one name per column (`columns=[\"a\", \"b\", \"c\"]`)","Or name the Series themselves (`pl.Series(\"a\", [1])`) and drop the columns argument","Compute names from the data instead of hardcoding: `columns=[s.name for s in data]` or `[f\"col_{i}\" for i in range(len(data))]`"],"exampleFix":"# before\ncols = [pl.Series(\"x\", [1, 2]), pl.Series(\"y\", [3, 4]), pl.Series(\"z\", [5, 6])]\npl.DataFrame(cols)\n# internal rename path with columns=[\"a\", \"b\"] -> ValueError: dimensions of columns arg (2) must match data dimensions (3)\n\n# after\npl.DataFrame(cols)  # keep the Series names: x, y, z\n# or rename with matching count:\ndf = pl.DataFrame(cols)\ndf.columns = [\"a\", \"b\", \"c\"]","handlingStrategy":"validation","validationCode":"import polars as pl\n\ndef apply_columns(data: list[pl.Series], columns: list[str] | None):\n    if columns is not None and len(columns) != len(data):\n        raise ValueError(f\"{len(columns)} names for {len(data)} columns\")\n    return pl.DataFrame(data)","typeGuard":"def names_match_data(columns: list[str] | None, data) -> bool:\n    \"\"\"True if columns is None or its length equals the number of data columns.\"\"\"\n    return columns is None or len(columns) == len(data)","tryCatchPattern":"try:\n    df = pl.DataFrame(data, columns=columns)  # or internal rename path\nexcept ValueError as e:\n    if \"dimensions of columns arg\" not in str(e):\n        raise\n    raise ValueError(\"column name list out of sync with data width — regenerate names\") from e","preventionTips":["Keep name lists and data generation in the same function so they cannot drift","Prefer naming Series at creation time over post-hoc column renames","Compute names from data length when the width varies: [f\"c{i}\" for i in range(len(data))]"],"tags":["dataframe-construction","schema","shape-mismatch","columns"],"backgroundTag":null,"analyzedSha":"df599052daf96e7a9cc30a3b0c6bd25d6947e3c0","analyzedAt":"2026-08-16T12:10:03.978Z","schemaVersion":2},"datasetVersion":"2026-08-16T13:17:31.715Z"}