pandas-dev/pandas · error · TypeError

to_numpy() got an unexpected keyword argument '{bad_keys}'

Error message

to_numpy() got an unexpected keyword argument '{bad_keys}'

What it means

Raised by Series/Index.to_numpy when extra **kwargs are passed but self.dtype is not an ExtensionDtype. For extension dtypes the kwargs forward to array.to_numpy; for numpy-backed dtypes those kwargs are unsupported and the first offending key is named.

Source

Thrown at pandas/core/base.py:700

        >>> ser.to_numpy(dtype=object)
        array([Timestamp('2000-01-01 00:00:00+0100', tz='CET'),
               Timestamp('2000-01-02 00:00:00+0100', tz='CET')],
              dtype=object)

        Or ``dtype='datetime64[ns]'`` to return an ndarray of native
        datetime64 values. The values are converted to UTC and the timezone
        info is dropped.

        >>> ser.to_numpy(dtype="datetime64[ns]")
        ... # doctest: +ELLIPSIS
        array(['1999-12-31T23:00:00.000000000', '2000-01-01T23:00:00...'],
              dtype='datetime64[ns]')
        """
        if isinstance(self.dtype, ExtensionDtype):
            return self.array.to_numpy(dtype, copy=copy, na_value=na_value, **kwargs)
        elif kwargs:
            bad_keys = next(iter(kwargs.keys()))
            raise TypeError(
                f"to_numpy() got an unexpected keyword argument '{bad_keys}'"
            )

        fillna = (
            na_value is not lib.no_default
            # no need to fillna with np.nan if we already have a float dtype
            and not (na_value is np.nan and np.issubdtype(self.dtype, np.floating))
        )

        values = self._values
        if fillna and self.hasnans:
            if not can_hold_element(values, na_value):
                # if we can't hold the na_value asarray either makes a copy or we
                # error before modifying values. The asarray later on thus won't make
                # another copy
                values = np.asarray(values, dtype=dtype)
            else:
                values = values.copy()

View on GitHub (pinned to 71959b8cb9)

Solutions

  1. Restrict kwargs to the documented set: dtype, copy, na_value are honored only when applicable.
  2. Branch on isinstance(s.dtype, pd.ExtensionDtype) before forwarding kwargs.
  3. Pre-fill NA values yourself via fillna before to_numpy.

Example fix

// before
arr = s.to_numpy(na_value=-1)  # s is int64 numpy-backed

// after
arr = s.fillna(-1).to_numpy()
Defensive patterns

Strategy: type-guard

Validate before calling

from pandas.api.types import is_extension_array_dtype
if not is_extension_array_dtype(s.dtype):
    bad = set(kwargs) - {'dtype','copy'}
    if bad:
        raise TypeError(f'unsupported to_numpy kwargs for numpy dtype: {bad}')

Type guard

def accepts_to_numpy_kwargs(s) -> bool:
    from pandas.api.types import is_extension_array_dtype
    return is_extension_array_dtype(s.dtype)

Try / catch

try:
    arr = s.to_numpy(**kwargs)
except TypeError as e:
    if 'unexpected keyword argument' in str(e):
        arr = s.fillna(kwargs.get('na_value')).to_numpy(
            dtype=kwargs.get('dtype'), copy=kwargs.get('copy', False))
    else:
        raise

Prevention

When it happens

Trigger: `numpy_backed_series.to_numpy(na_value=0)` or passing dtype/copy/na_value combinations on a plain int64/float64 Series that the numpy path does not accept.

Common situations: Generic helper code forwarding the same kwargs to all dtypes; assuming na_value is universally accepted; migrating from extension to numpy dtypes.

Related errors


AI-assisted analysis of pandas-dev/pandas@71959b8cb9 (2026-08-07). Data as JSON: /api/errors/4f0e1f0e48b43dd6. Report an issue: GitHub.