{"record":{"id":"1031363f6c0e67d8","repo":"pola-rs/polars","slug":"dimensions-of-schema-n-schema-cols-must-matc","errorCode":null,"errorMessage":"dimensions of `schema` ({n_schema_cols}) must match data dimensions ({n_columns})","messagePattern":"dimensions of `schema` \\((.+?)\\) must match data dimensions \\((.+?)\\)","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"py-polars/src/polars/_utils/construction/dataframe.py","lineNumber":1283,"sourceCode":"\n            elif orient == \"row\":\n                n_columns = shape[1]\n            elif orient == \"col\":\n                n_columns = shape[0]\n            else:\n                msg = f\"`orient` must be one of {{'col', 'row', None}}, got {orient!r}\"\n                raise ValueError(msg)\n        else:\n            if shape == ():\n                msg = \"cannot create DataFrame from zero-dimensional array\"\n            else:\n                msg = f\"cannot create DataFrame from array with more than two dimensions; shape = {shape}\"\n            raise ValueError(msg)\n\n    if schema is not None and len(schema) != n_columns:\n        if (n_schema_cols := len(schema)) != 1:\n            msg = f\"dimensions of `schema` ({n_schema_cols}) must match data dimensions ({n_columns})\"\n            raise ValueError(msg)\n        n_columns = n_schema_cols\n\n    column_names, schema_overrides = _unpack_schema(\n        schema, schema_overrides=schema_overrides, n_expected=n_columns\n    )\n\n    # Convert data to series\n    if structured_array:\n        data_series = [\n            pl.Series(\n                name=series_name,\n                values=data[record_name],\n                dtype=schema_overrides.get(record_name),\n                strict=strict,\n                nan_to_null=nan_to_null,\n            )._s\n            for series_name, record_name in zip(column_names, record_names, strict=True)\n        ]","sourceCodeStart":1265,"sourceCodeEnd":1301,"githubUrl":"https://github.com/pola-rs/polars/blob/df599052daf96e7a9cc30a3b0c6bd25d6947e3c0/py-polars/src/polars/_utils/construction/dataframe.py#L1265-L1301","documentation":"In the NumPy construction path, when a schema is supplied its length must equal the column count implied by the array shape and orient (shape[1] for row/None on 2D, shape[0] for col on 2D). The only exception is len(schema) == 1, which squeezes everything into a single named column; any other mismatch raises this ValueError.","triggerScenarios":"pl.DataFrame(np.zeros((3, 2)), schema=[\"a\", \"b\", \"c\"]); pl.DataFrame(np.arange(5), schema=[\"a\", \"b\"]); switching orient from \"col\" to \"row\" on a non-square array without updating the schema length.","commonSituations":"Array was transposed upstream so row/column counts swapped; hardcoded name lists drifting out of sync with generated data; 1D data assumed to be 2D.","solutions":["Compute the expected width from the shape and orient, then pass exactly that many names.","Omit schema, let polars infer, and rename afterwards: df.columns = [...].","For a 1D array you want named, pass exactly one name (the allowed len==1 squeeze) or reshape to (n, 1) first."],"exampleFix":"// before\narr = np.zeros((3, 2))\ndf = pl.DataFrame(arr, schema=[\"a\", \"b\", \"c\"])\n\n// after\ndf = pl.DataFrame(arr, schema=[\"a\", \"b\"])\n// or: df = pl.DataFrame(arr).rename({\"column_0\": \"a\", \"column_1\": \"b\"})","handlingStrategy":"validation","validationCode":"arr = np.asarray(value)\nn_cols = arr.shape[1] if (arr.ndim == 2 and orient in (None, \"row\")) else (arr.shape[0] if orient == \"col\" else 1)\nif schema is not None and len(schema) != n_cols and len(schema) != 1:\n    raise ValueError(f\"len(schema)={len(schema)} but array provides {n_cols} columns\")\ndf = pl.DataFrame(arr, schema=schema, orient=orient)","typeGuard":null,"tryCatchPattern":"try:\n    df = pl.DataFrame(arr, schema=schema, orient=orient)\nexcept ValueError as e:\n    if \"must match data dimensions\" in str(e):\n        df = pl.DataFrame(arr)  # infer names, rename afterwards\n        df.columns = list(schema)\n    else:\n        raise","preventionTips":["Compute name lists from the array shape instead of constants.","After changing orient, re-check len(schema) against the new axis.","Let polars infer names first and rename afterwards for dynamic data."],"tags":["numpy","schema","column-mismatch","dataframe"],"backgroundTag":null,"analyzedSha":"df599052daf96e7a9cc30a3b0c6bd25d6947e3c0","analyzedAt":"2026-08-16T12:10:03.978Z","schemaVersion":2},"datasetVersion":"2026-08-16T13:17:31.715Z"}