{"record":{"id":"928adfa676b93b05","repo":"pandas-dev/pandas","slug":"to-coo-requires-multiindex-with-nlevels-2","errorCode":null,"errorMessage":"to_coo requires MultiIndex with nlevels >= 2.","messagePattern":"to_coo requires MultiIndex with nlevels >= 2\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/sparse/scipy_sparse.py","lineNumber":157,"sourceCode":"\n    return values, i_coords, j_coords, i_labels, j_labels\n\n\ndef sparse_series_to_coo(\n    ss: Series,\n    row_levels: Iterable[int] = (0,),\n    column_levels: Iterable[int] = (1,),\n    sort_labels: bool = False,\n) -> tuple[scipy.sparse.coo_matrix, list[IndexLabel], list[IndexLabel]]:\n    \"\"\"\n    Convert a sparse Series to a scipy.sparse.coo_matrix using index\n    levels row_levels, column_levels as the row and column\n    labels respectively. Returns the sparse_matrix, row and column labels.\n    \"\"\"\n    import scipy.sparse\n\n    if ss.index.nlevels < 2:\n        raise ValueError(\"to_coo requires MultiIndex with nlevels >= 2.\")\n    if not ss.index.is_unique:\n        raise ValueError(\n            \"Duplicate index entries are not allowed in to_coo transformation.\"\n        )\n\n    # to keep things simple, only rely on integer indexing (not labels)\n    row_levels = [ss.index._get_level_number(x) for x in row_levels]\n    column_levels = [ss.index._get_level_number(x) for x in column_levels]\n\n    v, i, j, rows, columns = _to_ijv(\n        ss, row_levels=row_levels, column_levels=column_levels, sort_labels=sort_labels\n    )\n    sparse_matrix = scipy.sparse.coo_matrix(\n        (v, (i, j)), shape=(len(rows), len(columns))\n    )\n    return sparse_matrix, rows, columns\n\n","sourceCodeStart":139,"sourceCodeEnd":175,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/arrays/sparse/scipy_sparse.py#L139-L175","documentation":"Thrown by sparse_series_to_coo in pandas/core/arrays/sparse/scipy_sparse.py:157 when the Series index has fewer than 2 levels. COO matrix conversion splits MultiIndex levels between rows and columns, which is meaningless for a single-level or flat index — at minimum one row level and one column level are required.","triggerScenarios":"Calling ss.sparse.to_coo() on a sparse Series with a plain Index or a SingleElement-MultiIndex (nlevels==1). Calling to_coo on a Series whose MultiIndex was collapsed via droplevel(0).","commonSituations":"User assumes any sparse Series can be COO-converted but only MultiIndexed data qualifies. Index flattening earlier in the pipeline removed the second level.","solutions":["Rebuild a MultiIndex with at least 2 levels before calling to_coo, e.g. ss.index = pd.MultiIndex.from_arrays([a, b]).","If you genuinely have one level, use a different sparse representation (scipy.sparse.coo_matrix from explicit (data,(i,j)) tuples) rather than pandas to_coo.","Guard the call: if ss.index.nlevels >= 2: ss.sparse.to_coo()."],"exampleFix":"// before\ns = pd.Series([1,0,2], index=['a','b','c']).astype('Sparse[int]')\ns.sparse.to_coo()  # raises\n\n// after\ns.index = pd.MultiIndex.from_arrays([['a','b','c'], [0,1,2]])\ns.sparse.to_coo()","handlingStrategy":"validation","validationCode":"def to_coo_safe(ss, **kw):\n    if ss.index.nlevels < 2:\n        raise ValueError(f'need MultiIndex with >=2 levels, got {ss.index.nlevels}')\n    return ss.sparse.to_coo(**kw)","typeGuard":"import pandas as pd\ndef is_multiindex(obj) -> bool:\n    return isinstance(obj.index, pd.MultiIndex) and obj.index.nlevels >= 2","tryCatchPattern":"null","preventionTips":["Construct a MultiIndex explicitly before to_coo rather than relying on a flat index.","Check ss.index.nlevels >= 2 before invoking the sparse COO path.","If your data is naturally 1-D, choose a sparse representation that doesn't need a 2-D layout."],"tags":["sparse","scipy","coo","multiindex"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-14T00:17:10.932Z"}