Skip to content

Commit 221af87

Browse files
committed
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
1 parent 0fe491d commit 221af87

File tree

3 files changed

+17
-1
lines changed

3 files changed

+17
-1
lines changed

doc/source/whatsnew/v0.20.0.txt

+1
Original file line numberDiff line numberDiff line change
@@ -362,3 +362,4 @@ Bug Fixes
362362

363363

364364
- Bug in ``pd.read_csv()`` for the C engine where ``usecols`` were being indexed incorrectly with ``parse_dates`` (:issue:`14792`)
365+
- Bug in ``Series`` constructor when both ``copy=True`` and ``dtype`` argument is provided (:issue:`15125`)

pandas/core/series.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -237,7 +237,8 @@ def __init__(self, data=None, index=None, dtype=None, name=None,
237237
# create/copy the manager
238238
if isinstance(data, SingleBlockManager):
239239
if dtype is not None:
240-
data = data.astype(dtype=dtype, raise_on_error=False)
240+
data = data.astype(dtype=dtype, raise_on_error=False,
241+
copy=copy)
241242
elif copy:
242243
data = data.copy()
243244
else:

pandas/tests/series/test_constructors.py

+14
Original file line numberDiff line numberDiff line change
@@ -251,6 +251,20 @@ def test_constructor_sanitize(self):
251251
s = Series(np.array([1., 1., np.nan]), copy=True, dtype='i8')
252252
self.assertEqual(s.dtype, np.dtype('f8'))
253253

254+
def test_constructor_copy(self):
255+
# GH15125
256+
# test dtype parameter has no side effects on copy=True
257+
x = Series(np.array([1.]))
258+
y = pd.Series(x, copy=True, dtype=float)
259+
260+
# copy=True maintains original data in Series
261+
self.assertTrue(x.equals(y))
262+
263+
# changes to origin of copy does not affect the copy
264+
x[0] = 2.
265+
self.assertFalse(x.equals(y))
266+
self.assertEqual(y[0], 1.)
267+
254268
def test_constructor_pass_none(self):
255269
s = Series(None, index=lrange(5))
256270
self.assertEqual(s.dtype, np.float64)

0 commit comments

Comments
 (0)