Skip to content
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

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

Closed
3 tasks done
jamesmyatt opened this issue Nov 26, 2020 · 3 comments · Fixed by #42243
Closed
3 tasks done

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

jamesmyatt opened this issue Nov 26, 2020 · 3 comments · Fixed by #42243
Labels
Compat pandas objects compatability with Numpy or Python functions Enhancement
Milestone

Comments

@jamesmyatt
Copy link
Contributor

jamesmyatt commented Nov 26, 2020

  • 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

@jamesmyatt jamesmyatt added Bug Needs Triage Issue that has not been reviewed by a pandas team member labels Nov 26, 2020
@jamesmyatt
Copy link
Contributor Author

jamesmyatt commented Nov 26, 2020

In the short-term, I think it's probably acceptable for pandas to take the BitGenerator used by the input Generator (gen.bit_generator) and wrap it in a new RandomState, as for the workaround. What do you think?

But long-term it's probably best to convert everything to use Generator objects instead since this is the future. Not least because there's a reason that Numpy has moved away from MT19937.

@jamesmyatt
Copy link
Contributor Author

Since the minimum NumPy version should now be 1.17 (according to NEP29), which provides the new Generator objects, are these changes that can now be made?

jamesmyatt added a commit to jamesmyatt/pandas that referenced this issue Apr 6, 2021
@jreback
Copy link
Contributor

jreback commented Apr 6, 2021

@jamesmyatt we are still supporting numpy 1.6 in upcoming release

but not averse to actually bumping it (separate PR)

jamesmyatt added a commit to jamesmyatt/pandas that referenced this issue Apr 6, 2021
@lithomas1 lithomas1 added Enhancement Compat pandas objects compatability with Numpy or Python functions and removed Bug Needs Triage Issue that has not been reviewed by a pandas team member labels Jun 25, 2021
@jreback jreback added this to the 1.4 milestone Jul 1, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Compat pandas objects compatability with Numpy or Python functions Enhancement
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants