Skip to content

Commit a0550dd

Browse files
committed
Merge pull request #8671 from jreback/coerce
BUG: Bug in setitem with empty indexer and unwanted coercion of dtypes (GH8669)
2 parents eecf160 + 6dc2199 commit a0550dd

File tree

3 files changed

+33
-5
lines changed

3 files changed

+33
-5
lines changed

doc/source/whatsnew/v0.15.1.txt

+2-1
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,8 @@ Bug Fixes
140140

141141

142142

143-
- Bug in numeric index operations of add/sub with Float/Index Index with numpy arrays (:issue:`8608`)
143+
- Bug in numeric index operations of add/sub with Float/Index Index with numpy arrays (:issue:`8608`
144+
- Bug in setitem with empty indexer and unwanted coercion of dtypes (:issue:`8669`)
144145

145146

146147

pandas/core/internals.py

+24-3
Original file line numberDiff line numberDiff line change
@@ -549,10 +549,31 @@ def setitem(self, indexer, value):
549549
"different length than the value")
550550

551551
try:
552+
553+
def _is_scalar_indexer(indexer):
554+
# treat a len 0 array like a scalar
555+
# return True if we are all scalar indexers
556+
557+
if arr_value.ndim == 1:
558+
if not isinstance(indexer, tuple):
559+
indexer = tuple([indexer])
560+
561+
def _is_ok(idx):
562+
563+
if np.isscalar(idx):
564+
return True
565+
elif isinstance(idx, slice):
566+
return False
567+
return len(idx) == 0
568+
569+
return all([ _is_ok(idx) for idx in indexer ])
570+
return False
571+
572+
552573
# setting a single element for each dim and with a rhs that could be say a list
553-
# GH 6043
554-
if arr_value.ndim == 1 and (
555-
np.isscalar(indexer) or (isinstance(indexer, tuple) and all([ np.isscalar(idx) for idx in indexer ]))):
574+
# or empty indexers (so no astyping)
575+
# GH 6043, 8669 (empty)
576+
if _is_scalar_indexer(indexer):
556577
values[indexer] = value
557578

558579
# if we are an exact match (ex-broadcasting),

pandas/tests/test_indexing.py

+7-1
Original file line numberDiff line numberDiff line change
@@ -1043,6 +1043,13 @@ def test_loc_setitem_frame(self):
10431043
expected = DataFrame(dict(A = Series(val1,index=keys1), B = Series(val2,index=keys2))).reindex(index=index)
10441044
assert_frame_equal(df, expected)
10451045

1046+
# GH 8669
1047+
# invalid coercion of nan -> int
1048+
df = DataFrame({'A' : [1,2,3], 'B' : np.nan })
1049+
df.loc[df.B > df.A, 'B'] = df.A
1050+
expected = DataFrame({'A' : [1,2,3], 'B' : np.nan})
1051+
assert_frame_equal(df, expected)
1052+
10461053
# GH 6546
10471054
# setting with mixed labels
10481055
df = DataFrame({1:[1,2],2:[3,4],'a':['a','b']})
@@ -1055,7 +1062,6 @@ def test_loc_setitem_frame(self):
10551062
df.loc[0,[1,2]] = [5,6]
10561063
assert_frame_equal(df, expected)
10571064

1058-
10591065
def test_loc_setitem_frame_multiples(self):
10601066
# multiple setting
10611067
df = DataFrame({ 'A' : ['foo','bar','baz'],

0 commit comments

Comments
 (0)