pola-rs/polars · error · ModuleNotFoundError

'numpy' is required to convert numpy dtype {dtype!r}

Error message

'numpy' is required to convert numpy dtype {dtype!r}

What it means

Raised when polars must map a numpy dtype to a Series constructor but numpy is not installed in the environment. The lookup helper references the 'np' namespace inside a try block, and the resulting NameError is converted into ModuleNotFoundError. It signals a missing optional dependency, not a problem with your data.

Source

Thrown at py-polars/src/polars/datatypes/constructor.py:157

) -> Callable[..., PySeries]:
    """Get the right PySeries constructor for the given Polars dtype."""
    if _NUMPY_TYPE_TO_CONSTRUCTOR is None:
        _set_numpy_to_constructor()
    try:
        return _NUMPY_TYPE_TO_CONSTRUCTOR[dtype]  # type:ignore[index]
    except KeyError:
        if len(values) > 0:
            first_non_nan = next(
                (v for v in values if isinstance(v, np.ndarray) or v == v), None
            )
            if isinstance(first_non_nan, str):
                return PySeries.new_str
            if isinstance(first_non_nan, bytes):
                return PySeries.new_binary
        return PySeries.new_object
    except NameError:  # pragma: no cover
        msg = f"'numpy' is required to convert numpy dtype {dtype!r}"
        raise ModuleNotFoundError(msg) from None


def py_type_to_constructor(py_type: type[Any]) -> Callable[..., PySeries]:
    """Get the right PySeries constructor for the given Python dtype."""
    py_type = (
        next((tp for tp in _PY_TYPE_TO_CONSTRUCTOR if issubclass(py_type, tp)), py_type)
        if py_type not in _PY_TYPE_TO_CONSTRUCTOR
        else py_type
    )
    return _PY_TYPE_TO_CONSTRUCTOR.get(py_type, PySeries.new_object)

View on GitHub (pinned to df599052da)

Solutions

  1. Install numpy: pip install numpy (or pip install 'polars[numpy]')
  2. If numpy cannot be installed, pass pure-Python containers (list/tuple) with an explicit polars dtype so the numpy constructor lookup is never reached

Example fix

# before (environment without numpy)
pl.Series(np_dtype_object_values)  # ModuleNotFoundError

# after
# pip install numpy
# or: pass plain Python data
pl.Series([1, 2, 3], dtype=pl.Int64)
Defensive patterns

Strategy: validation

Validate before calling

import importlib.util

if importlib.util.find_spec('numpy') is None:
    raise SystemExit('numpy is required for numpy-dtyped inputs: pip install numpy')

import numpy as np  # safe now
s = pl.Series(values)

Try / catch

try:
    s = pl.Series(values)
except ModuleNotFoundError as e:
    if "'numpy' is required" in str(e):
        raise RuntimeError('install numpy: pip install numpy') from e
    raise

Prevention

When it happens

Trigger: Calling pl.Series(...) or related constructor helpers with a numpy dtype object (or values that require numpy dtype resolution) in an environment where 'import numpy' fails, hitting the except NameError branch in numpy_type_to_constructor.

Common situations: Slim Docker images or CI runners where numpy was pruned to save space; a venv rebuilt without numpy after polars was installed; partial/failed numpy installs; relying on polars' optional numpy extra that is not present.

Related errors


AI-assisted analysis of pola-rs/polars@df599052da (2026-08-16). Data as JSON: /api/errors/3d6d0c103a248ec9. Report an issue: GitHub.