pandas-dev/pandas · error · TypeError
mask must be a 1D list-like
Error message
mask must be a 1D list-like
What it means
Raised by _coerce_to_data_and_mask when an explicitly supplied mask has ndim != 1. The mask must be a 1-D boolean array aligned elementwise with values; a 2-D or scalar mask is rejected because there is no defined correspondence to the 1-D data.
Source
Thrown at pandas/core/arrays/numeric.py:215
if is_nan_na():
mask = np.isnan(values)
else:
mask = np.zeros(len(values), dtype=np.bool_)
if dtype_cls.__name__.strip("_").startswith(("I", "U")):
wrong = np.isnan(values)
if wrong.any():
raise ValueError("Cannot cast NaN value to Integer dtype.")
elif is_nan_na():
mask = libmissing.is_numeric_na(values)
else:
# is_numeric_na will raise on non-numeric NAs
libmissing.is_numeric_na(values)
mask = libmissing.is_pdna_or_none(values)
else:
assert len(mask) == len(values)
if mask.ndim != 1:
raise TypeError("mask must be a 1D list-like")
# infer dtype if needed
if dtype is None:
dtype = default_dtype
else:
dtype = dtype.numpy_dtype
if is_integer_dtype(dtype) and values.dtype.kind == "f" and len(values) > 0:
if mask.all():
values = np.ones(values.shape, dtype=dtype)
else:
idx = np.nanargmax(values)
if int(values[idx]) != original[idx]:
# We have ints that lost precision during the cast.
inferred_type = lib.infer_dtype(original, skipna=True)
if (
inferred_type not in ["floating", "mixed-integer-float"]
and not mask.any()View on GitHub (pinned to 71959b8cb9)
Solutions
- Flatten the mask to 1-D matching len(values): mask = mask.ravel().
- Select the corresponding column of the mask: mask = mask_2d[:, col_index].
- Re-derive the mask from values via np.isnan/np.isna after ensuring 1-D data.
Example fix
// before NumericArray(vals, mask_2d) # raises: mask must be a 1D list-like // after NumericArray(vals, mask_2d.ravel())
Defensive patterns
Strategy: validation
Validate before calling
import numpy as np
def ensure_1d_mask(mask, n):
m = np.asarray(mask, dtype=bool)
if m.ndim != 1:
raise TypeError(f"mask must be 1D, got ndim={m.ndim}")
if m.shape[0] != n:
raise ValueError("mask length must match values")
return m Type guard
def is_1d_mask(mask) -> bool:
import numpy as np
return np.asarray(mask).ndim == 1 Try / catch
try:
arr = NumericArray(values, mask)
except TypeError as e:
if "mask must be a 1D list-like" in str(e):
import numpy as np
arr = NumericArray(values, np.asarray(mask, dtype=bool).ravel())
else:
raise Prevention
- Always build masks as 1-D boolean arrays of length len(values).
- Flatten masks sliced from 2-D structures.
- Prefer pd.array(...) which constructs the mask internally.
When it happens
Trigger: Constructing NumericArray(values, mask) where mask is a 2-D boolean array, or passing a multi-dimensional mask through pd.array / from_arrow internal paths.
Common situations: Building a masked array manually with a mask sliced from a 2-D structure; reshaping masks incorrectly during ETL.
Related errors
- values must be a 1D list-like
- Array with ndim > 2 is not supported.
- values.shape and mask.shape must match
- invalid dtype specified {dtype}
- No such keys(s): {pat!r}
AI-assisted analysis of pandas-dev/pandas@71959b8cb9 (2026-08-07).
Data as JSON: /api/errors/f98fdb3b63ad5c36.
Report an issue: GitHub.