Skip to content

Commit 5cf4f02

Browse files
author
Matti Airas
committed
Fixes GH9099: Support simultaneous copy and dtype args in DataFrame init
1 parent f7af818 commit 5cf4f02

File tree

3 files changed

+16
-4
lines changed

3 files changed

+16
-4
lines changed

doc/source/whatsnew/v0.16.0.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,3 +51,4 @@ Bug Fixes
5151

5252
- Fixed compatibility issue in ``DatetimeIndex`` affecting architectures where ``numpy.int_`` defaults to ``numpy.int32`` (:issue:`8943`)
5353
- Bug in ``MultiIndex.has_duplicates`` when having many levels causes an indexer overflow (:issue:`9075`)
54+
- DataFrame now properly supports simultaneous ``copy`` and ``dtype`` arguments in constructor (:issue:`9099`)

pandas/core/generic.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -121,11 +121,11 @@ def _init_mgr(self, mgr, axes=None, dtype=None, copy=False):
121121
mgr = mgr.reindex_axis(
122122
axe, axis=self._get_block_manager_axis(a), copy=False)
123123

124-
# do not copy BlockManager unless explicitly done
125-
if copy and dtype is None:
124+
# make a copy if explicitly requested
125+
if copy:
126126
mgr = mgr.copy()
127-
elif dtype is not None:
128-
# avoid copy if we can
127+
if dtype is not None:
128+
# avoid further copies if we can
129129
if len(mgr.blocks) > 1 or mgr.blocks[0].values.dtype != dtype:
130130
mgr = mgr.astype(dtype=dtype)
131131
return mgr

pandas/tests/test_frame.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2489,6 +2489,17 @@ def test_constructor_cast_failure(self):
24892489
# this is ok
24902490
df['foo2'] = np.ones((4,2)).tolist()
24912491

2492+
def test_constructor_dtype_copy(self):
2493+
orig_df = DataFrame({
2494+
'col1': [1.],
2495+
'col2': [2.],
2496+
'col3': [3.]})
2497+
2498+
new_df = pd.DataFrame(orig_df, dtype=float, copy=True)
2499+
2500+
new_df['col1'] = 200.
2501+
self.assertEqual(orig_df['col1'][0], 1.)
2502+
24922503
def test_constructor_dtype_nocast_view(self):
24932504
df = DataFrame([[1, 2]])
24942505
should_be_view = DataFrame(df, dtype=df[0].dtype)

0 commit comments

Comments
 (0)