pandas-dev/pandas · error · ValueError

Length of 'value' does not match. Got

Error message

Length of 'value' does not match. Got ({len(value)})  expected {len(self)}

What it means

Raised by ArrowExtensionArray.fillna when `value` is an ndarray or ExtensionArray whose length differs from len(self). Array-like fill values must align positionally with the target array, so a length mismatch is rejected before attempting to box the value into pyarrow.

Solutions

  1. Align lengths explicitly: ensure len(value) == len(arr) before calling fillna.
  2. Use a Series and let pandas align on the index: pd.Series(arr).fillna(pd.Series(value)).
  3. Broadcast a scalar instead of an array when the fill is uniform.
  4. Reindex the fill array to match before passing: value = value[:len(arr)] or use np.broadcast_to.

Example fix

# before
arr = pd.array([1, None, 3, None], dtype="int64[pyarrow]")
fill = pd.array([0, 0, 0], dtype="int64[pyarrow]")
arr.fillna(fill)  # raises ValueError

# after
fill = pd.array([0, 0, 0, 0], dtype="int64[pyarrow]")
arr.fillna(fill)
Defensive patterns

Strategy: validation

Validate before calling

def safe_fillna_array(arr, value):
    if hasattr(value, '__len__') and not isinstance(value, str):
        if len(value) != len(arr):
            raise ValueError(f'len(value)={len(value)} != len(arr)={len(arr)}')
    return arr.fillna(value)

Type guard

def length_matches(value, target_len: int) -> bool:
    return not hasattr(value, '__len__') or len(value) == target_len

Prevention

When it happens

Trigger: arr.fillna(other_array) where len(other_array) != len(arr); passing a column from a differently-shaped DataFrame as the fill value; using a boolean mask of the wrong length; chaining operations that produced an array of unexpected size.

Common situations: Filling NA from a parallel column whose index was not aligned; off-by-one in computing the fill array; mixing arrays from different groupby groups; broadcasting assumptions that do not hold for fillna.

Related errors


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

Appendix: source

Thrown at pandas/core/arrays/arrow/array.py:1731

        Length: 6, dtype: int64[pyarrow]
        """
        if not self._hasna:
            return self.copy()

        if isinstance(value, dict):
            raise TypeError(
                "ExtensionArray.fillna does not support filling with a dict. "
                "Use Series.fillna instead."
            )

        if limit is not None:
            return super().fillna(value=value, limit=limit, copy=copy)

        if isinstance(value, (np.ndarray, ExtensionArray)):
            # Similar to check_value_size, but we do not mask here since we may
            #  end up passing it to the super() method.
            if len(value) != len(self):
                raise ValueError(
                    f"Length of 'value' does not match. Got ({len(value)}) "
                    f" expected {len(self)}"
                )

        try:
            fill_value = self._box_pa(value, pa_type=self._pa_array.type)
        except pa.ArrowTypeError as err:
            msg = f"Invalid value '{value!s}' for dtype '{self.dtype}'"
            raise TypeError(msg) from err

        try:
            return self._from_pyarrow_array(
                _safe_fill_null(self._pa_array, fill_value=fill_value)
            )
        except pa.ArrowNotImplementedError:
            # ArrowNotImplementedError: Function 'coalesce' has no kernel
            #   matching input types (duration[ns], duration[ns])
            # TODO: remove try/except wrapper if/when pyarrow implements

View on GitHub (pinned to 3b7651241d)