pandas-dev/pandas · error · TypeError
Cannot construct {type(self).__name__} from scalar data. Pas
Error message
Cannot construct {type(self).__name__} from scalar data. Pass a sequence instead. What it means
Raised in SparseArray.__init__ when the `data` argument is a scalar (is_scalar(data) is True). SparseArray models a 1-D sequence of stored values; a single scalar has no length to define sparsity, so pandas asks for a sequence instead. This is a TypeError, distinct from value-level validation.
Source
Thrown at pandas/core/arrays/sparse/array.py:425
# 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 71959b8cb9)
Solutions
- Wrap the scalar in a list: SparseArray([5]).
- Pass the whole column/Series rather than a scalar element.
- If you need a length-1 sparse array, build it explicitly: SparseArray([fill]*1) or use np.array([x]).
Example fix
// before pd.arrays.SparseArray(df.loc[0, 'val']) // after pd.arrays.SparseArray([df.loc[0, 'val']])
Defensive patterns
Strategy: type-guard
Validate before calling
import pandas as pd
from pandas.api.types import is_scalar
def sparse_array_safe(data, **kw):
if is_scalar(data):
data = [data]
return pd.arrays.SparseArray(data, **kw) Type guard
def is_sequence_for_sparse(data) -> bool:
from pandas.api.types import is_scalar
return not is_scalar(data) Try / catch
try:
return pd.arrays.SparseArray(data)
except TypeError as e:
if 'scalar data' in str(e):
return pd.arrays.SparseArray([data])
raise Prevention
- Always wrap scalars in a list before SparseArray.
- Pass whole columns/Series, not single cells.
- Guard with pandas.api.types.is_scalar.
When it happens
Trigger: pd.arrays.SparseArray(5); pd.arrays.SparseArray(np.nan); passing a single int/float where a list was intended, e.g. SparseArray(df.loc[i,'val']).
Common situations: Iterating a DataFrame cell-by-cell instead of column-wise; refactors that replaced a list literal with a scalar; config values mistakenly wrapped directly.
Related errors
- 'data' must have a single column, not '{ncol}'
- Unable to avoid copy while creating an array as requested.
- Cannot modify read-only array
- SparseArray does not support item assignment via setitem
- SparseArray does not support in-place sort
AI-assisted analysis of pandas-dev/pandas@71959b8cb9 (2026-08-07).
Data as JSON: /api/errors/59629e1304609e71.
Report an issue: GitHub.