From 7b0c959930ae0e10d62a40520a7fed7b3ad9eff6 Mon Sep 17 00:00:00 2001 From: Rouz Azari Date: Fri, 13 Jan 2017 11:47:39 -0800 Subject: [PATCH] BUG: Fix Series constructor when copy=True Updates Series constructor to include copy argument when dtype argument is also provided. Adds tests for copy parameter. xref #15125 --- doc/source/whatsnew/v0.20.0.txt | 2 +- pandas/core/series.py | 3 ++- pandas/tests/series/test_constructors.py | 16 ++++++++++++++++ 3 files changed, 19 insertions(+), 2 deletions(-) diff --git a/doc/source/whatsnew/v0.20.0.txt b/doc/source/whatsnew/v0.20.0.txt index 5c26bb2985e75..2a825edd0e98a 100644 --- a/doc/source/whatsnew/v0.20.0.txt +++ b/doc/source/whatsnew/v0.20.0.txt @@ -366,7 +366,7 @@ Bug Fixes - +- Bug in ``Series`` constructor when both ``copy=True`` and ``dtype`` arguments are provided (:issue:`15125`) - Bug in ``pd.read_csv()`` for the C engine where ``usecols`` were being indexed incorrectly with ``parse_dates`` (:issue:`14792`) - Bug in ``Series.dt.round`` inconsistent behaviour on NAT's with different arguments (:issue:`14940`) \ No newline at end of file diff --git a/pandas/core/series.py b/pandas/core/series.py index ab1498c617467..d967e2d02d41f 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -237,7 +237,8 @@ def __init__(self, data=None, index=None, dtype=None, name=None, # create/copy the manager if isinstance(data, SingleBlockManager): if dtype is not None: - data = data.astype(dtype=dtype, raise_on_error=False) + data = data.astype(dtype=dtype, raise_on_error=False, + copy=copy) elif copy: data = data.copy() else: diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py index a7e3ebdfc43d0..ee4940384b612 100644 --- a/pandas/tests/series/test_constructors.py +++ b/pandas/tests/series/test_constructors.py @@ -251,6 +251,22 @@ def test_constructor_sanitize(self): s = Series(np.array([1., 1., np.nan]), copy=True, dtype='i8') self.assertEqual(s.dtype, np.dtype('f8')) + def test_constructor_copy(self): + # GH15125 + # test dtype parameter has no side effects on copy=True + for data in [[1.], np.array([1.])]: + x = Series(data) + y = pd.Series(x, copy=True, dtype=float) + + # copy=True maintains original data in Series + tm.assert_series_equal(x, y) + + # changes to origin of copy does not affect the copy + x[0] = 2. + self.assertFalse(x.equals(y)) + self.assertEqual(x[0], 2.) + self.assertEqual(y[0], 1.) + def test_constructor_pass_none(self): s = Series(None, index=lrange(5)) self.assertEqual(s.dtype, np.float64)