Skip to content

Commit 870eca6

Browse files
committed
always copy data when inserting into DataFrame. failing reverse op dtype=object unit test
1 parent af7647b commit 870eca6

File tree

3 files changed

+26
-2
lines changed

3 files changed

+26
-2
lines changed

pandas/core/frame.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -825,8 +825,8 @@ def _insert_item(self, key, value):
825825
if hasattr(value, '__iter__'):
826826
if isinstance(value, Series):
827827
if value.index.equals(self.index):
828-
# no need to copy
829-
value = value.values
828+
# copy the values
829+
value = value.values.copy()
830830
else:
831831
value = value.reindex(self.index).values
832832
else:
@@ -836,6 +836,8 @@ def _insert_item(self, key, value):
836836
value = np.array(value)
837837
if value.dtype.type == np.str_:
838838
value = np.array(value, dtype=object)
839+
else:
840+
value = value.copy()
839841
else:
840842
value = np.repeat(value, len(self.index))
841843

pandas/tests/test_frame.py

+7
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,13 @@ def test_setitem(self):
8989
self.assertEqual(smaller['col10'].dtype, np.object_)
9090
self.assert_((smaller['col10'] == ['1', '2']).all())
9191

92+
def test_setitem_always_copy(self):
93+
s = self.frame['A'].copy()
94+
self.frame['E'] = s
95+
96+
self.frame['E'][5:10] = np.nan
97+
self.assert_(notnull(s[5:10]).all())
98+
9299
def test_setitem_boolean(self):
93100
df = self.frame.copy()
94101
values = self.frame.values

pandas/tests/test_series.py

+15
Original file line numberDiff line numberDiff line change
@@ -453,6 +453,21 @@ def test_operators_corner(self):
453453
expected = self.ts.values[:-5] + int_ts.values
454454
self.assert_(np.array_equal(added[:-5], expected))
455455

456+
def test_operators_reverse_object(self):
457+
# GH 56
458+
arr = Series(np.random.randn(10), index=np.arange(10),
459+
dtype=object)
460+
461+
def _check_op(arr, op):
462+
result = op(1., arr)
463+
expected = op(1., arr.astype(float))
464+
assert_series_equal(result, expected)
465+
466+
_check_op(arr, operator.add)
467+
_check_op(arr, operator.sub)
468+
_check_op(arr, operator.mul)
469+
_check_op(arr, operator.div)
470+
456471
def test_operators_frame(self):
457472
# rpow does not work with DataFrame
458473
df = DataFrame({'A' : self.ts})

0 commit comments

Comments
 (0)