diff --git a/doc/source/whatsnew/v0.18.2.txt b/doc/source/whatsnew/v0.18.2.txt index 907ca6f185e0a..ddefb2849d1f2 100644 --- a/doc/source/whatsnew/v0.18.2.txt +++ b/doc/source/whatsnew/v0.18.2.txt @@ -56,6 +56,8 @@ API changes - Non-convertible dates in an excel date column will be returned without conversion and the column will be ``object`` dtype, rather than raising an exception (:issue:`10001`) - Compat with ``np.round`` and timestamps (:issue:`12811`) - An ``UnsupportedFunctionCall`` error is now raised if numpy ufuncs like ``np.mean`` are called on groupby or resample objects (:issue:`12811`) +- Calls to ``.sample()`` will respect random seed set via ``numpy.random.seed(n)`` (:issue:`13161`) + .. _whatsnew_0182.api.tolist: diff --git a/pandas/core/common.py b/pandas/core/common.py index 64bfbdde0c5c3..8af6b78a050f3 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -2062,7 +2062,7 @@ def _random_state(state=None): state : int, np.random.RandomState, None. If receives an int, passes to np.random.RandomState() as seed. If receives an np.random.RandomState object, just returns object. - If receives `None`, returns an np.random.RandomState object. + If receives `None`, returns np.random. If receives anything else, raises an informative ValueError. Default None. @@ -2076,7 +2076,7 @@ def _random_state(state=None): elif isinstance(state, np.random.RandomState): return state elif state is None: - return np.random.RandomState() + return np.random else: raise ValueError("random_state must be an integer, a numpy " "RandomState, or None") diff --git a/pandas/tests/test_common.py b/pandas/tests/test_common.py index 090669681fb4f..e1b186f6c21e5 100644 --- a/pandas/tests/test_common.py +++ b/pandas/tests/test_common.py @@ -695,7 +695,7 @@ def test_random_state(): com._random_state(state2).uniform(), npr.RandomState(10).uniform()) # check with no arg random state - assert isinstance(com._random_state(), npr.RandomState) + assert com._random_state() is np.random # Error for floats or strings with tm.assertRaises(ValueError): diff --git a/pandas/tests/test_generic.py b/pandas/tests/test_generic.py index ba282f0107d71..2bad2fabcfc57 100644 --- a/pandas/tests/test_generic.py +++ b/pandas/tests/test_generic.py @@ -415,6 +415,14 @@ def test_sample(self): o.sample(frac=0.7, random_state=np.random.RandomState(test)), o.sample(frac=0.7, random_state=np.random.RandomState(test))) + os1, os2 = [], [] + for _ in range(2): + np.random.seed(test) + os1.append(o.sample(n=4)) + os2.append(o.sample(frac=0.7)) + self._compare(*os1) + self._compare(*os2) + # Check for error when random_state argument invalid. with tm.assertRaises(ValueError): o.sample(random_state='astring!')