{"record":{"id":"67b2a3f0da785424","repo":"pandas-dev/pandas","slug":"random-state-must-be-an-integer-array-like-a-bit","errorCode":null,"errorMessage":"random_state must be an integer, array-like, a BitGenerator, Generator, a numpy RandomState, or None","messagePattern":"random_state must be an integer, array-like, a BitGenerator, Generator, a numpy RandomState, or None","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pandas/core/common.py","lineNumber":475,"sourceCode":"        If receives anything else, raises an informative ValueError.\n\n        Default None.\n\n    Returns\n    -------\n    np.random.RandomState or np.random.Generator. If state is None, returns np.random\n\n    \"\"\"\n    if is_integer(state) or isinstance(state, (np.ndarray, np.random.BitGenerator)):\n        return np.random.RandomState(state)\n    elif isinstance(state, np.random.RandomState):\n        return state\n    elif isinstance(state, np.random.Generator):\n        return state\n    elif state is None:\n        return np.random  # type: ignore[return-value]\n    else:\n        raise ValueError(\n            \"random_state must be an integer, array-like, a BitGenerator, Generator, \"\n            \"a numpy RandomState, or None\"\n        )\n\n\n_T = TypeVar(\"_T\")  # Secondary TypeVar for use in pipe's type hints\n\n\n@overload\ndef pipe(\n    obj: _T,\n    func: Callable[Concatenate[_T, P], T],\n    *args: P.args,\n    **kwargs: P.kwargs,\n) -> T: ...\n\n\n@overload","sourceCodeStart":457,"sourceCodeEnd":493,"githubUrl":"https://github.com/pandas-dev/pandas/blob/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/common.py#L457-L493","documentation":"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.","triggerScenarios":"`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`.","commonSituations":"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.","solutions":["Convert string seeds to int: `df.sample(random_state=int(seed_str))`.","Pass an int for reproducibility: `random_state=42`, or a Generator: `random_state=np.random.default_rng(42)`.","If passing an array-like seed, ensure it is an int ndarray accepted by np.random.RandomState."],"exampleFix":"# before\nseed = os.environ['SEED']   # str\ndf.sample(random_state=seed, n=5)\n\n# after\nseed = int(os.environ['SEED'])\ndf.sample(random_state=seed, n=5)","handlingStrategy":"validation","validationCode":"import numpy as np\n\ndef validate_random_state(state):\n    ok = (state is None or isinstance(state, (int, np.ndarray, np.random.BitGenerator,\n                                              np.random.Generator, np.random.RandomState)))\n    if not ok:\n        raise ValueError('random_state must be int, array-like, BitGenerator, Generator, RandomState, or None')\n    return state","typeGuard":"import numpy as np\n\ndef is_valid_random_state(state) -> bool:\n    return state is None or isinstance(state, (int, np.ndarray, np.random.BitGenerator,\n                                               np.random.Generator, np.random.RandomState))","tryCatchPattern":"try:\n    sample = df.sample(random_state=state, n=5)\nexcept ValueError as e:\n    if 'random_state must be' in str(e):\n        sample = df.sample(random_state=int(state), n=5)\n    else:\n        raise","preventionTips":["Convert string seeds to int: random_state=int(seed_str).","Use np.random.default_rng(seed) for the modern Generator API.","Validate config-supplied RNG args before passing to sample."],"tags":["random-state","sampling","validation","rng","valueerror"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}