pandas-dev/pandas · error · ValueError

random_state must be an integer, array-like, a…

Error message

random_state must be an integer, array-like, a BitGenerator, Generator, a numpy RandomState, or None

What it means

Raised by the random_state helper used by df.sample, Series.sample, DataFrame.sample, and other methods that accept a random_state argument. The helper accepts int, array-like, np.random.BitGenerator, np.random.RandomState, np.random.Generator, or None; anything else (string, float, tuple, custom object) raises ValueError listing the accepted types.

Solutions

  1. Pass an int seed: df.sample(random_state=42).
  2. Pass an np.random.Generator: df.sample(random_state=np.random.default_rng(0)).
  3. Convert types at the boundary: random_state=int(cfg['seed']) if cfg['seed'] else None.
  4. Pass None for global NumPy RNG.

Example fix

// before
df.sample(random_state='42')
// after
seed = int('42')
df.sample(random_state=seed)
Defensive patterns

Strategy: validation

Validate before calling

import numpy as np
acceptable = (int, np.integer, np.ndarray, np.random.BitGenerator, np.random.RandomState, np.random.Generator, type(None))
if not isinstance(rs, acceptable):
    raise ValueError(f'bad random_state: {rs!r}')
df.sample(random_state=rs)

Type guard

def is_valid_random_state(rs) -> bool:
    import numpy as np
    if rs is None:
        return True
    return isinstance(rs, (int, np.integer, np.ndarray, np.random.BitGenerator, np.random.RandomState, np.random.Generator))

Prevention

When it happens

Trigger: df.sample(random_state='42'); df.sample(random_state=3.14); df.sample(random_state=(1,2)); passing a Python random.Random instance (not accepted — only NumPy RandomState/Generator).

Common situations: Passing a string seed from config without converting to int; mixing Python's random module with pandas; passing a float seed; passing a tuple/seed object from an ML framework.

Related errors


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

Appendix: source

Thrown at pandas/core/common.py:475

        If receives anything else, raises an informative ValueError.

        Default None.

    Returns
    -------
    np.random.RandomState or np.random.Generator. If state is None, returns np.random

    """
    if is_integer(state) or isinstance(state, (np.ndarray, np.random.BitGenerator)):
        return np.random.RandomState(state)
    elif isinstance(state, np.random.RandomState):
        return state
    elif isinstance(state, np.random.Generator):
        return state
    elif state is None:
        return np.random  # type: ignore[return-value]
    else:
        raise ValueError(
            "random_state must be an integer, array-like, a BitGenerator, Generator, "
            "a numpy RandomState, or None"
        )


_T = TypeVar("_T")  # Secondary TypeVar for use in pipe's type hints


@overload
def pipe(
    obj: _T,
    func: Callable[Concatenate[_T, P], T],
    *args: P.args,
    **kwargs: P.kwargs,
) -> T: ...


@overload

View on GitHub (pinned to 3b7651241d)