{"record":{"id":"6a012d9d94268476","repo":"pandas-dev/pandas","slug":"index-length-mismatch-len-index-vs-n","errorCode":null,"errorMessage":"Index length mismatch: {len(index)} vs. {N}","messagePattern":"Index length mismatch: (.+?) vs\\. (.+?)","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/sparse/accessor.py","lineNumber":504,"sourceCode":"        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":486,"sourceCodeEnd":506,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/arrays/sparse/accessor.py#L486-L506","documentation":"Raised by SparseFrameAccessor._prep_index when len(index) does not equal N, the first dimension of the source sparse matrix. The row labels must exactly match the matrix's row count.","triggerScenarios":"pd.DataFrame.sparse.from_spmatrix(mat, index=some_series) where len(some_series) != mat.shape[0]; passing a DatetimeIndex of the wrong length.","commonSituations":"Index built from a different sample; matrix transposed but index not flipped; reusing labels from a previous run after slicing the matrix.","solutions":["Pass index=None to let pandas assign a default RangeIndex.","Construct index from shape: index=pd.RangeIndex(mat.shape[0]).","Slice/align the index to the matrix before calling: index = index[:mat.shape[0]]."],"exampleFix":"# before\npd.DataFrame.sparse.from_spmatrix(mat, index=old_index)  # len mismatch\n# after\nidx = pd.RangeIndex(mat.shape[0])\npd.DataFrame.sparse.from_spmatrix(mat, index=idx)","handlingStrategy":"validation","validationCode":"def index_matches_matrix(index, mat) -> bool:\n    return index is None or len(index) == mat.shape[0]","typeGuard":"def valid_index_for(index, mat) -> bool:\n    return index is None or len(list(index)) == mat.shape[0]","tryCatchPattern":"try:\n    df = pd.DataFrame.sparse.from_spmatrix(mat, index=index)\nexcept ValueError as e:\n    if 'Index length mismatch' in str(e):\n        df = pd.DataFrame.sparse.from_spmatrix(mat)\n    else:\n        raise","preventionTips":["Slice/align index to mat.shape[0] before calling.","Pass index=None when default RangeIndex is acceptable.","Build index from pd.RangeIndex(mat.shape[0]) to guarantee length."],"tags":["pandas","sparse","shape","scipy"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}