{"record":{"id":"59629e1304609e71","repo":"pandas-dev/pandas","slug":"cannot-construct-type-self-name-from-scalar","errorCode":null,"errorMessage":"Cannot construct {type(self).__name__} from scalar data. Pass a sequence instead.","messagePattern":"Cannot construct (.+?) from scalar data\\. Pass a sequence instead\\.","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/sparse/array.py","lineNumber":430,"sourceCode":"            # TODO: make kind=None, and use data.kind?\n            data = data.sp_values\n\n        # Handle use-provided dtype\n        if isinstance(dtype, str):\n            # Two options: dtype='int', regular numpy dtype\n            # or dtype='Sparse[int]', a sparse dtype\n            try:\n                dtype = SparseDtype.construct_from_string(dtype)\n            except TypeError:\n                dtype = pandas_dtype(dtype)\n\n        if isinstance(dtype, SparseDtype):\n            if fill_value is None:\n                fill_value = dtype.fill_value\n            dtype = dtype.subtype\n\n        if is_scalar(data):\n            raise TypeError(\n                f\"Cannot construct {type(self).__name__} from scalar data. \"\n                \"Pass a sequence instead.\"\n            )\n\n        if dtype is not None:\n            dtype = pandas_dtype(dtype)\n\n        # TODO: disentangle the fill_value dtype inference from\n        # dtype inference\n        if data is None:\n            # TODO: What should the empty dtype be? Object or float?\n\n            # error: Argument \"dtype\" to \"array\" has incompatible type\n            # \"Union[ExtensionDtype, dtype[Any], None]\"; expected \"Union[dtype[Any],\n            # None, type, _SupportsDType, str, Union[Tuple[Any, int], Tuple[Any,\n            # Union[int, Sequence[int]]], List[Any], _DTypeDict, Tuple[Any, Any]]]\"\n            data = np.array([], dtype=dtype)  # type: ignore[arg-type]\n","sourceCodeStart":412,"sourceCodeEnd":448,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/arrays/sparse/array.py#L412-L448","documentation":"Raised as TypeError by SparseArray.__new__/__init__ when is_scalar(data) is True. SparseArray models a 1-D sequence of values plus a fill value; a single scalar has no length to sparsify, so the constructor refuses it.","triggerScenarios":"pd.arrays.SparseArray(0); pd.arrays.SparseArray(np.float64(1.0)); passing a Python int/float/str as data.","commonSituations":"Default-argument fallthrough that yields a scalar instead of a list; reading a single cell from a DataFrame and trying to wrap it; helper that returns a scalar where a sequence was expected.","solutions":["Wrap the scalar in a list: pd.arrays.SparseArray([value]).","Repeat to a known length: pd.arrays.SparseArray([value] * n).","Build a length-1 Series with dtype='Sparse[...]' instead."],"exampleFix":"# before\npd.arrays.SparseArray(0)\n# after\npd.arrays.SparseArray([0])","handlingStrategy":"type-guard","validationCode":"import numpy as np\nfrom pandas.api.types import is_scalar\n\ndef is_sequence_data(data) -> bool:\n    return not is_scalar(data) and hasattr(data, '__len__') or isinstance(data, np.ndarray)","typeGuard":"from collections.abc import Sized, Iterable\nimport numpy as np\n\ndef sparse_array_safe(data) -> bool:\n    return isinstance(data, (list, tuple, range, np.ndarray, pd.Series))","tryCatchPattern":"try:\n    arr = pd.arrays.SparseArray(data)\nexcept TypeError as e:\n    if 'scalar data' in str(e):\n        arr = pd.arrays.SparseArray([data])\n    else:\n        raise","preventionTips":["Always wrap single values in a list/tuple for SparseArray.","Use pd.Series([value], dtype='Sparse[...]') for one-element sparse data.","Add an is_scalar(data) check at the boundary of helper functions."],"tags":["pandas","sparse","constructor","scalar"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}