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 the mask passed alongside values has mask.ndim != 1. The mask is normally only supplied via the internal fast-path that splits an existing masked array into _data/_mask, both of which are 1-D. A non-1-D mask indicates an internal/caller contract violation: the mask must be a flat boolean array matching the length of values.

Solutions

  1. Ensure the mask is 1-D: mask = np.asarray(mask).ravel() and confirm len(mask) == len(values).
  2. If you are subclassing NumericArray, recompute the mask via the standard _coerce_to_data_and_mask path instead of constructing it manually.
  3. Report as a pandas bug if reached through the public API without a custom mask.

Example fix

# before (internal)
mask = np.zeros((3, 2), dtype=bool)  # 2-D
arr = IntegerArray(values, mask)        # raises

# after
mask = np.zeros(values.shape[0], dtype=bool)  # 1-D
Defensive patterns

Strategy: validation

Validate before calling

import numpy as np

def assert_valid_mask(values, mask):
    mask = np.asarray(mask, dtype=bool)
    assert mask.ndim == 1, 'mask must be 1-D'
    assert mask.shape[0] == values.shape[0], 'mask length mismatch'
    return mask

Type guard

def is_flat_bool_mask(mask, values) -> bool:
    import numpy as np
    m = np.asarray(mask)
    return m.ndim == 1 and m.dtype == bool and m.shape[0] == np.asarray(values).shape[0]

Try / catch

try:
    NumericArray(values, mask)
except TypeError as e:
    if 'mask must be a 1D' in str(e):
        mask = np.asarray(mask, dtype=bool).ravel()
        NumericArray(values, mask)
    else:
        raise

Prevention

When it happens

Trigger: Internally: extracting _data/_mask from a higher-dimensional masked array (rare; the values.ndim check at line 188 usually fires first). Direct: calling NumericArray(data, mask) with a 2-D mask ndarray. Subclass code that synthesizes a mask of the wrong shape.

Common situations: Almost always an internal/library bug or a subclass overriding construction with a mis-shaped mask; end users rarely hit it because the public API never accepts a mask argument.

Related errors


AI-assisted analysis of pandas-dev/pandas@3b7651241d (2026-08-11). Data as JSON: /api/errors/f98fdb3b63ad5c36. Report an issue: GitHub.

Appendix: 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 3b7651241d)