Description
-
I have checked that this issue has not already been reported.
-
I have confirmed this bug exists on the latest version of pandas.
-
(optional) I have confirmed this bug exists on the master branch of pandas.
Code Sample, a copy-pastable example
import pandas as pd
import numpy as np
df = pd.DataFrame({'num_legs': [2, 4, 8, 0],
'num_wings': [2, 0, 0, 0],
'num_specimen_seen': [10, 2, 1, 8]},
index=['falcon', 'dog', 'spider', 'fish'])
rng = np.random.default_rng()
df.sample(random_state=rng)
Output:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-34-d27bfa21cee7> in <module>
4 index=['falcon', 'dog', 'spider', 'fish'])
5 rng = np.random.default_rng()
----> 6 df.sample(random_state=rng)
C:\tools\miniconda3\envs\pandas-dev\lib\site-packages\pandas\core\generic.py in sample(self, n, frac, replace, weights, random_state, axis)
4914
4915 # Process random_state argument
-> 4916 rs = com.random_state(random_state)
4917
4918 # Check weights for compliance
C:\tools\miniconda3\envs\pandas-dev\lib\site-packages\pandas\core\common.py in random_state(state)
429 return np.random
430 else:
--> 431 raise ValueError(
432 (
433 "random_state must be an integer, array-like, a BitGenerator, "
ValueError: random_state must be an integer, array-like, a BitGenerator, a numpy RandomState, or None
Problem description
Best practice since Numpy 1.17 for creating random number generators is to use numpy.random.default_rng
:
https://numpy.org/doc/stable/reference/random/index.html?highlight=random#quick-start. This returns a numpy.random.Generator
object. It should not be necessary to extract the underlying BitGenerator
or convert it manually to a legacy numpy.random.RandomState
.
Closest issues I can find are #28440 (mentions performance only) and #32503. Code is here:
Line 366 in 78d1498
Current simplest workaround is as follows. I've confirmed that it advances rng
.
df.sample(random_state=rng.bit_generator)
Expected Output
Code above should not throw an error.
Output of pd.show_versions()
pandas : 1.1.4
numpy : 1.19.4
pytz : 2020.4
dateutil : 2.8.1
pip : 20.2.4
setuptools : 49.6.0.post20201009
Cython : None
pytest : 6.1.2
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : 2.11.2
IPython : 7.19.0
pandas_datareader: None
bs4 : None
bottleneck : None
fsspec : None
fastparquet : None
gcsfs : None
matplotlib : 3.3.3
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : 2.0.0
pytables : None
pyxlsb : None
s3fs : None
scipy : 1.5.3
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
xlwt : None
numba : 0.51.2