Skip to content

BUG: Support numpy.random.Generator as random_state input #40813

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions pandas/core/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -425,6 +425,8 @@ def random_state(state=None):
or (not np_version_under1p18 and isinstance(state, np.random.BitGenerator))
):
return np.random.RandomState(state)
elif not np_version_under1p18 and isinstance(state, np.random.Generator):
return np.random.RandomState(state.bit_generator)
elif isinstance(state, np.random.RandomState):
return state
elif state is None:
Expand Down
12 changes: 12 additions & 0 deletions pandas/tests/test_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,18 @@ def test_random_state():
== npr.RandomState(npr.PCG64(11)).uniform()
)

# Check Generators
# GH38100
if not np_version_under1p17:
rng1 = npr.default_rng(4)
rng2 = npr.default_rng(4)
assert (
com.random_state(rng1).uniform()
== npr.RandomState(rng2.bit_generator).uniform()
)
# Check base RNGs have advanced correctly
assert rng1.uniform() == rng2.uniform()

# Error for floats or strings
msg = (
"random_state must be an integer, array-like, a BitGenerator, "
Expand Down