pandas-dev/pandas · error · TypeError
Cannot construct from scalar data. Pass a sequence instead.
Error message
Cannot construct {type(self).__name__} from scalar data. Pass a sequence instead. What it means
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.
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.
Example fix
# before pd.arrays.SparseArray(0) # after pd.arrays.SparseArray([0])
Defensive patterns
Strategy: type-guard
Validate before calling
import numpy as np
from pandas.api.types import is_scalar
def is_sequence_data(data) -> bool:
return not is_scalar(data) and hasattr(data, '__len__') or isinstance(data, np.ndarray) Type guard
from collections.abc import Sized, Iterable
import numpy as np
def sparse_array_safe(data) -> bool:
return isinstance(data, (list, tuple, range, np.ndarray, pd.Series)) Try / catch
try:
arr = pd.arrays.SparseArray(data)
except TypeError as e:
if 'scalar data' in str(e):
arr = pd.arrays.SparseArray([data])
else:
raise Prevention
- 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.
When it happens
Trigger: pd.arrays.SparseArray(0); pd.arrays.SparseArray(np.float64(1.0)); passing a Python int/float/str as data.
Common situations: 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.
Related errors
- NumpyExtensionArray must be 1-dimensional.
- Can only use the '.sparse' accessor with Sparse data.
- Cannot create a from a MultiIndex.
- cannot evaluate scalar only bool ops
- Cannot modify read-only array
AI-assisted analysis of pandas-dev/pandas@3b7651241d (2026-08-11).
Data as JSON: /api/errors/59629e1304609e71.
Report an issue: GitHub.
Appendix: source
Thrown at pandas/core/arrays/sparse/array.py:430
# TODO: make kind=None, and use data.kind?
data = data.sp_values
# Handle use-provided dtype
if isinstance(dtype, str):
# Two options: dtype='int', regular numpy dtype
# or dtype='Sparse[int]', a sparse dtype
try:
dtype = SparseDtype.construct_from_string(dtype)
except TypeError:
dtype = pandas_dtype(dtype)
if isinstance(dtype, SparseDtype):
if fill_value is None:
fill_value = dtype.fill_value
dtype = dtype.subtype
if is_scalar(data):
raise TypeError(
f"Cannot construct {type(self).__name__} from scalar data. "
"Pass a sequence instead."
)
if dtype is not None:
dtype = pandas_dtype(dtype)
# TODO: disentangle the fill_value dtype inference from
# dtype inference
if data is None:
# TODO: What should the empty dtype be? Object or float?
# error: Argument "dtype" to "array" has incompatible type
# "Union[ExtensionDtype, dtype[Any], None]"; expected "Union[dtype[Any],
# None, type, _SupportsDType, str, Union[Tuple[Any, int], Tuple[Any,
# Union[int, Sequence[int]]], List[Any], _DTypeDict, Tuple[Any, Any]]]"
data = np.array([], dtype=dtype) # type: ignore[arg-type]
View on GitHub (pinned to 3b7651241d)