{"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":1292,"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":1274,"sourceCodeEnd":1310,"githubUrl":"https://github.com/pola-rs/polars/blob/fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e/py-polars/src/polars/_utils/construction/dataframe.py#L1274-L1310","documentation":"In `numpy_to_pydf`, when a `schema` is supplied its length must match the number of columns derived from the data. The only exception: a 1-D array with a 1-element schema is allowed. Otherwise ValueError is raised.","triggerScenarios":"pl.from_numpy(arr, schema=[...]) where len(schema) != arr.shape[1] (for 2-D) or != 1 (for 1-D arrays).","commonSituations":"Hard-coded column name lists that drift from the data after changing array width; reusing a schema from a different dataset; forgetting a 2-D array with a single column still has n_columns = 1 but an array widened by a code change.","solutions":["Make len(schema) equal the array's second dimension (number of columns).","Pass schema as a dict of {name: dtype} built from the actual array width.","If unsure, omit `schema` and let Polars infer names, then rename with .rename()."],"exampleFix":"// before\npl.from_numpy(arr, schema=['a', 'b'])  # arr has 3 columns\n// after\npl.from_numpy(arr, schema=['a', 'b', 'c'])  # or schema={f'c{i}': pl.Float64 for i in range(arr.shape[1])}","handlingStrategy":"validation","validationCode":"n_cols = arr.shape[1] if arr.ndim == 2 else 1\nif schema is not None and len(schema) != n_cols and not (arr.ndim == 1 and len(schema) == 1):\n    raise ValueError(f'schema has {len(schema)} names but data has {n_cols} columns')","typeGuard":null,"tryCatchPattern":"try:\n    df = pl.from_numpy(arr, schema=schema)\nexcept ValueError as e:\n    if 'must match data dimensions' in str(e):\n        schema = [f'c{i}' for i in range(arr.shape[-1])]\n        df = pl.from_numpy(arr, schema=schema)\n    else:\n        raise","preventionTips":["Derive schema names from arr.shape[1] instead of hard-coding lists.","Use dict schemas {name: dtype} built programmatically.","Add a unit test asserting len(schema) == arr.shape[1] when schemas are configured."],"tags":["polars","schema","numpy","shape-mismatch"],"backgroundTag":"shape-mismatch","analyzedSha":"fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e","analyzedAt":"2026-09-18T22:14:11.667Z","contentChangedAt":"2026-09-18T22:14:11.667Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}