{"record":{"id":"190a11920fe0c126","repo":"pandas-dev/pandas","slug":"column-length-mismatch-len-columns-vs-k","errorCode":null,"errorMessage":"Column length mismatch: {len(columns)} vs. {K}","messagePattern":"Column length mismatch: (.+?) vs\\. (.+?)","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/sparse/accessor.py","lineNumber":502,"sourceCode":"    @staticmethod\n    def _prep_index(data, index, columns):\n        from pandas.core.indexes.api import (\n            default_index,\n            ensure_index,\n        )\n\n        N, K = data.shape\n        if index is None:\n            index = default_index(N)\n        else:\n            index = ensure_index(index)\n        if columns is None:\n            columns = default_index(K)\n        else:\n            columns = ensure_index(columns)\n\n        if len(columns) != K:\n            raise ValueError(f\"Column length mismatch: {len(columns)} vs. {K}\")\n        if len(index) != N:\n            raise ValueError(f\"Index length mismatch: {len(index)} vs. {N}\")\n        return index, columns\n","sourceCodeStart":484,"sourceCodeEnd":506,"githubUrl":"https://github.com/pandas-dev/pandas/blob/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/arrays/sparse/accessor.py#L484-L506","documentation":"Raised in SparseFrameAccessor._prep_index (used by from_spmatrix) when the number of column labels supplied does not equal K, the number of columns in the source sparse matrix. The labels cannot be mapped 1:1 to columns, so construction is rejected.","triggerScenarios":"pd.DataFrame.sparse.from_spmatrix(scipy.sparse.eye(3), columns=['a','b']); passing a column list from a different-shaped matrix; reusing a stale columns list after the matrix changed shape.","commonSituations":"Hard-coded column lists that drift from the matrix width; slicing the sparse matrix but forgetting to slice the columns; off-by-one in column generation.","solutions":["Size columns to the matrix: pass columns=None to let pandas default to RangeIndex, or build columns = [f'c{i}' for i in range(mat.shape[1])].","Assert len(columns) == mat.shape[1] before calling.","If columns come from another df, align after building: result.columns = source.columns."],"exampleFix":"// before\npd.DataFrame.sparse.from_spmatrix(mat, columns=['a','b'])\n// after\npd.DataFrame.sparse.from_spmatrix(mat, columns=[f'c{i}' for i in range(mat.shape[1])])","handlingStrategy":"validation","validationCode":"import pandas as pd\n\ndef from_spmatrix_safe(mat, columns=None, index=None):\n    N, K = mat.shape\n    if columns is not None and len(columns) != K:\n        raise ValueError(f'columns len {len(columns)} != matrix cols {K}')\n    return pd.DataFrame.sparse.from_spmatrix(mat, index=index, columns=columns)","typeGuard":"def columns_match_matrix(columns, mat) -> bool:\n    return columns is None or len(columns) == mat.shape[1]","tryCatchPattern":"try:\n    return pd.DataFrame.sparse.from_spmatrix(mat, columns=columns)\nexcept ValueError as e:\n    if 'Column length mismatch' in str(e):\n        columns = [f'c{i}' for i in range(mat.shape[1])]\n        return pd.DataFrame.sparse.from_spmatrix(mat, columns=columns)\n    raise","preventionTips":["Pass columns=None or size them to mat.shape[1].","Re-derive columns from the matrix after slicing.","Assert len(columns)==mat.shape[1] before construction."],"tags":["pandas","sparse","dataframe","shape-mismatch","scipy"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}