{"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":553,"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":535,"sourceCodeEnd":571,"githubUrl":"https://github.com/pandas-dev/pandas/blob/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/arrays/sparse/array.py#L535-L571","documentation":"Raised in SparseArray.from_spmatrix when the input scipy sparse matrix has more than one column. SparseArray is 1-D, so only a single-column matrix can be flattened into it; multi-column matrices must go through DataFrame.sparse.from_spmatrix instead.","triggerScenarios":"pd.arrays.SparseArray.from_spmatrix(scipy.sparse.eye(3)); passing a CSR/CSC matrix with shape (n, k>1); from_spmatrix(mat) where mat was built from a 2-D array.","commonSituations":"Treating a 2-D sparse matrix as 1-D; reusing a matrix constructor that defaults to square shape; forgetting that scipy.sparse differentiates 1-D vs 2-D.","solutions":["Use DataFrame.sparse.from_spmatrix for multi-column matrices.","Reshape/slice the matrix to one column first: mat = scipy.sparse.csc_matrix(vec).reshape(-1,1).","If you genuinely have one column, ensure shape is (n,1): assert mat.shape[1] == 1."],"exampleFix":"// before\npd.arrays.SparseArray.from_spmatrix(scipy.sparse.eye(3))\n// after\npd.DataFrame.sparse.from_spmatrix(scipy.sparse.eye(3))","handlingStrategy":"validation","validationCode":"import pandas as pd\n\ndef from_spmatrix_1d(mat):\n    if mat.shape[1] != 1:\n        raise ValueError(f'matrix has {mat.shape[1]} columns; use DataFrame.sparse.from_spmatrix')\n    return pd.arrays.SparseArray.from_spmatrix(mat)","typeGuard":"def is_single_column_matrix(mat) -> bool:\n    return hasattr(mat, 'shape') and len(mat.shape) == 2 and mat.shape[1] == 1","tryCatchPattern":"try:\n    return pd.arrays.SparseArray.from_spmatrix(mat)\nexcept ValueError as e:\n    if 'single column' in str(e):\n        return pd.DataFrame.sparse.from_spmatrix(mat)\n    raise","preventionTips":["Check mat.shape[1]==1 before SparseArray.from_spmatrix.","Use DataFrame.sparse.from_spmatrix for 2-D matrices.","Reshape vectors to (n,1) explicitly."],"tags":["pandas","sparse","sparse-array","scipy","shape-mismatch"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}