pandas-dev/pandas · error · ValueError

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

Error message

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

What it means

Raised by pandas.core.common.random_state (pandas/core/common.py:475), the helper behind the `random_state` argument of DataFrame.sample, DataFrame.sample, shuffle, and many stochastic methods. It accepts int, array-like, np.random.BitGenerator, np.random.Generator, np.random.RandomState, or None; any other type is rejected to guarantee a usable RNG.

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 71959b8cb9)

Solutions

  1. Convert string seeds to int: `df.sample(random_state=int(seed_str))`.
  2. Pass an int for reproducibility: `random_state=42`, or a Generator: `random_state=np.random.default_rng(42)`.
  3. If passing an array-like seed, ensure it is an int ndarray accepted by np.random.RandomState.

Example fix

# before
seed = os.environ['SEED']   # str
df.sample(random_state=seed, n=5)

# after
seed = int(os.environ['SEED'])
df.sample(random_state=seed, n=5)
Defensive patterns

Strategy: validation

Validate before calling

import numpy as np

def validate_random_state(state):
    ok = (state is None or isinstance(state, (int, np.ndarray, np.random.BitGenerator,
                                              np.random.Generator, np.random.RandomState)))
    if not ok:
        raise ValueError('random_state must be int, array-like, BitGenerator, Generator, RandomState, or None')
    return state

Type guard

import numpy as np

def is_valid_random_state(state) -> bool:
    return state is None or isinstance(state, (int, np.ndarray, np.random.BitGenerator,
                                               np.random.Generator, np.random.RandomState))

Try / catch

try:
    sample = df.sample(random_state=state, n=5)
except ValueError as e:
    if 'random_state must be' in str(e):
        sample = df.sample(random_state=int(state), n=5)
    else:
        raise

Prevention

When it happens

Trigger: `df.sample(random_state='42')` (string), `df.sample(random_state=3.14)` (float), `df.sample(random_state=[1,2])` only if not coercible, or passing a custom RNG object that is none of the accepted types. Also `random_state=True`.

Common situations: Reading a seed from config/env as a string ('42') without conversion; passing a float seed; version mismatch where code assumed an older/looser acceptance.

Related errors


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