Skip to content

BUG: random_state should permit numpy.random.Generator #38100

Closed
@jamesmyatt

Description

@jamesmyatt
  • 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:

def random_state(state=None):

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()

INSTALLED VERSIONS ------------------ commit : 67a3d42 python : 3.8.6.final.0 python-bits : 64 OS : Windows OS-release : 10 Version : 10.0.18362 machine : AMD64 processor : Intel64 Family 6 Model 142 Stepping 12, GenuineIntel byteorder : little LC_ALL : None LANG : en_US.UTF-8 LOCALE : English_United Kingdom.1252

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Compatpandas objects compatability with Numpy or Python functionsEnhancement

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions