{"record":{"id":"3cfb7d535856150d","repo":"pandas-dev/pandas","slug":"data-must-have-a-single-column-not-ncol","errorCode":null,"errorMessage":"'data' must have a single column, not '{ncol}'","messagePattern":"'data' must have a single column, not '(.+?)'","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/sparse/array.py","lineNumber":558,"sourceCode":"            sparse matrix with a single column.\n\n        Returns\n        -------\n        SparseArray\n\n        Examples\n        --------\n        >>> import scipy.sparse\n        >>> mat = scipy.sparse.coo_matrix((4, 1))\n        >>> pd.arrays.SparseArray.from_spmatrix(mat)\n        <SparseArray>\n        [0.0, 0.0, 0.0, 0.0]\n        Length: 4, dtype: Sparse[float64, 0.0]\n        \"\"\"\n        length, ncol = data.shape\n\n        if ncol != 1:\n            raise ValueError(f\"'data' must have a single column, not '{ncol}'\")\n\n        # our sparse index classes require that the positions be strictly\n        # increasing. So we need to sort loc, and arr accordingly.\n        data_csc = data.tocsc()\n        data_csc.sort_indices()\n        arr = data_csc.data\n        idx = data_csc.indices\n\n        zero = np.array(0, dtype=arr.dtype).item()\n        dtype = SparseDtype(arr.dtype, zero)\n        index = IntIndex(length, idx)\n\n        return cls._simple_new(arr, index, dtype)\n\n    def __array__(\n        self, dtype: NpDtype | None = None, copy: bool | None = None\n    ) -> np.ndarray:\n        if self.sp_index.ngaps == 0:","sourceCodeStart":540,"sourceCodeEnd":576,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/arrays/sparse/array.py#L540-L576","documentation":"Raised by SparseArray.from_spmatrix when the source scipy sparse matrix has more than one column. The Series/SparseArray model is 1-D, so only single-column matrices (shape (N, 1)) can be flattened into a SparseArray.","triggerScenarios":"pd.arrays.SparseArray.from_spmatrix(scipy.sparse.csr_matrix((3,2))); passing a multi-column CSC/CSR/COO matrix.","commonSituations":"Treating a 2-D sparse matrix as a 1-D vector; wanting one column but constructing the matrix with the wrong shape; forgetting to slice the matrix first.","solutions":["Select a single column: SparseArray.from_spmatrix(mat[:, col]).","For multi-column data, use pd.DataFrame.sparse.from_spmatrix(mat) instead.","Reshape to (N, 1) explicitly if you truly have one vector."],"exampleFix":"# before\npd.arrays.SparseArray.from_spmatrix(mat)  # mat.shape == (5, 3)\n# after\npd.arrays.SparseArray.from_spmatrix(mat[:, 0])\n# or, for all columns\npd.DataFrame.sparse.from_spmatrix(mat)","handlingStrategy":"validation","validationCode":"def matrix_is_single_column(mat) -> bool:\n    return mat.ndim == 2 and mat.shape[1] == 1","typeGuard":"def single_column_sparse_matrix(mat) -> bool:\n    return getattr(mat, 'shape', (0, 0))[1] == 1","tryCatchPattern":"try:\n    arr = pd.arrays.SparseArray.from_spmatrix(mat)\nexcept ValueError as e:\n    if 'single column' in str(e):\n        arr = pd.arrays.SparseArray.from_spmatrix(mat[:, [0]])\n    else:\n        raise","preventionTips":["Slice mat[:, [col]] before from_spmatrix for SparseArray.","Use pd.DataFrame.sparse.from_spmatrix for multi-column matrices.","Check mat.shape[1] == 1 in your sparse-loading helper."],"tags":["pandas","sparse","scipy","shape"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}