Skip to content

Commit 0e219d7

Browse files
rouzazarijreback
authored andcommitted
BUG: Fix Series constructor when copy=True
Updates Series constructor to include copy argument when dtype argument is also provided. closes #15125 Author: Rouz Azari <[email protected]> Closes #15128 from rouzazari/series_dtype_param_no_side_effects_when_copy_true and squashes the following commits: 7b0c959 [Rouz Azari] BUG: Fix Series constructor when copy=True
1 parent a19b0d8 commit 0e219d7

File tree

3 files changed

+19
-2
lines changed

3 files changed

+19
-2
lines changed

doc/source/whatsnew/v0.20.0.txt

+1-1
Original file line numberDiff line numberDiff line change
@@ -366,7 +366,7 @@ Bug Fixes
366366

367367

368368

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

372372
- Bug in ``Series.dt.round`` inconsistent behaviour on NAT's with different arguments (:issue:`14940`)

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

+16
Original file line numberDiff line numberDiff line change
@@ -251,6 +251,22 @@ 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+
for data in [[1.], np.array([1.])]:
258+
x = Series(data)
259+
y = pd.Series(x, copy=True, dtype=float)
260+
261+
# copy=True maintains original data in Series
262+
tm.assert_series_equal(x, y)
263+
264+
# changes to origin of copy does not affect the copy
265+
x[0] = 2.
266+
self.assertFalse(x.equals(y))
267+
self.assertEqual(x[0], 2.)
268+
self.assertEqual(y[0], 1.)
269+
254270
def test_constructor_pass_none(self):
255271
s = Series(None, index=lrange(5))
256272
self.assertEqual(s.dtype, np.float64)

0 commit comments

Comments
 (0)