{"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/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/arrays/sparse/accessor.py#L486-L506","documentation":"Raised in SparseFrameAccessor._prep_index when the supplied row index length does not equal N, the number of rows of the source sparse matrix. The index must label every row, so a mismatch is rejected.","triggerScenarios":"pd.DataFrame.sparse.from_spmatrix(scipy.sparse.eye(3), index=[1,2]); passing a DatetimeIndex from a different-length source; reusing an index after filtering the matrix rows.","commonSituations":"Index inherited from a pre-filter df that had more/fewer rows than the matrix; timezone/time mismatches producing wrong-length indexes; concat/slice drift.","solutions":["Pass index=None to default to RangeIndex, or build index = existing_index[:mat.shape[0]].","Assert len(index) == mat.shape[0] before calling.","Re-derive the index from the matrix shape: index = pd.RangeIndex(mat.shape[0])."],"exampleFix":"// before\npd.DataFrame.sparse.from_spmatrix(mat, index=df.index)\n// after\npd.DataFrame.sparse.from_spmatrix(mat, index=df.index[:mat.shape[0]])","handlingStrategy":"validation","validationCode":"import pandas as pd\n\ndef from_spmatrix_safe_index(mat, index=None):\n    N, _ = mat.shape\n    if index is not None and len(index) != N:\n        raise ValueError(f'index len {len(index)} != matrix rows {N}')\n    return pd.DataFrame.sparse.from_spmatrix(mat, index=index)","typeGuard":"def index_match_matrix(index, mat) -> bool:\n    return index is None or len(index) == mat.shape[0]","tryCatchPattern":"try:\n    return pd.DataFrame.sparse.from_spmatrix(mat, index=index)\nexcept ValueError as e:\n    if 'Index length mismatch' in str(e):\n        return pd.DataFrame.sparse.from_spmatrix(mat)  # default RangeIndex\n    raise","preventionTips":["Pass index=None when unsure, or slice to mat.shape[0].","Derive the index from a source frame aligned to the matrix rows.","Assert len(index)==mat.shape[0] 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"}