{"record":{"id":"40f40f7eb2773fa7","repo":"pandas-dev/pandas","slug":"expected-dimension-1-data","errorCode":null,"errorMessage":"expected dimension <= 1 data","messagePattern":"expected dimension <= 1 data","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/sparse/array.py","lineNumber":2112,"sourceCode":"    \"\"\"\n    Convert ndarray to sparse format\n\n    Parameters\n    ----------\n    arr : ndarray\n    kind : {'block', 'integer'}\n    fill_value : NaN or another value\n    dtype : np.dtype, optional\n    copy : bool, default False\n\n    Returns\n    -------\n    (sparse_values, index, fill_value) : (ndarray, SparseIndex, Scalar)\n    \"\"\"\n    assert isinstance(arr, np.ndarray)\n\n    if arr.ndim > 1:\n        raise TypeError(\"expected dimension <= 1 data\")\n\n    if fill_value is None:\n        fill_value = na_value_for_dtype(arr.dtype)\n\n    if isna(fill_value):\n        mask = notna(arr)\n    else:\n        # cast to object comparison to be safe\n        if is_string_dtype(arr.dtype):\n            arr = arr.astype(object)\n\n        if is_object_dtype(arr.dtype):\n            # element-wise equality check method in numpy doesn't treat\n            # each element type, eg. 0, 0.0, and False are treated as\n            # same. So we have to check the both of its type and value.\n            mask = splib.make_mask_object_ndarray(arr, fill_value)\n        else:\n            mask = arr != fill_value","sourceCodeStart":2094,"sourceCodeEnd":2130,"githubUrl":"https://github.com/pandas-dev/pandas/blob/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/arrays/sparse/array.py#L2094-L2130","documentation":"Raised by the module-level _make_sparse helper (used by the SparseArray constructor and astype) when the input ndarray has arr.ndim > 1. SparseArray only models 1-D sparsity, so a 2-D array would need an unsupported sp_index shape; the constructor refuses up front.","triggerScenarios":"pd.arrays.SparseArray(np.zeros((3,4))), pd.Series(np.eye(3)).astype('Sparse[int64]') (rare; mostly direct ndarray), or piping a 2-D matrix through a code path expecting a vector.","commonSituations":"Treating a DataFrame column slice as 1-D when it is actually 2-D (e.g. df[['x']] vs df['x']), or applying sparse conversion to a feature matrix expecting per-column sparse arrays.","solutions":["Flatten explicitly if appropriate: pd.arrays.SparseArray(arr.ravel()).","Build sparse arrays per column: [pd.arrays.SparseArray(c) for c in arr.T].","For 2-D sparse storage use scipy.sparse directly (and pd.DataFrame.sparse.from_spmatrix)."],"exampleFix":"// before\nsa = pd.arrays.SparseArray(np.zeros((3, 4)))  # raises 'expected dimension <= 1'\n\n// after\nsa = pd.arrays.SparseArray(np.zeros((3, 4)).ravel())","handlingStrategy":"type-guard","validationCode":"import numpy as np\nimport pandas as pd\n\ndef to_sparse_1d(values, fill_value=None):\n    arr = np.asarray(values)\n    if arr.ndim > 1:\n        raise TypeError(f'expected 1-D, got ndim={arr.ndim}')\n    return pd.arrays.SparseArray(arr, fill_value=fill_value)","typeGuard":"import numpy as np\n\ndef is_1d(values) -> bool:\n    return np.asarray(values).ndim <= 1","tryCatchPattern":"try:\n    sa = pd.arrays.SparseArray(arr)\nexcept TypeError as e:\n    if 'expected dimension' in str(e):\n        sa = pd.arrays.SparseArray(np.asarray(arr).ravel())\n    else:\n        raise","preventionTips":["Select single columns with df['x'] not df[['x']] before sparse conversion","Use scipy.sparse for 2-D sparse storage instead of SparseArray","Validate ndim == 1 at the boundary to your sparse pipeline"],"tags":["sparse","constructor","ndim","shape"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}