Skip to content

Commit f46df11

Browse files
authored
BUG: Series.__setitem__ positional raising ValuError (#45232)
1 parent a8f966b commit f46df11

File tree

3 files changed

+16
-5
lines changed

3 files changed

+16
-5
lines changed

doc/source/whatsnew/v1.5.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,7 @@ Interval
151151

152152
Indexing
153153
^^^^^^^^
154-
-
154+
- Bug in :meth:`Series.__setitem__` with a non-integer :class:`Index` when using an integer key to set a value that cannot be set inplace where a ``ValueError`` was raised insead of casting to a common dtype (:issue:`45070`)
155155
-
156156

157157
Missing

pandas/core/series.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -1098,8 +1098,9 @@ def __setitem__(self, key, value) -> None:
10981098
FutureWarning,
10991099
stacklevel=find_stack_level(),
11001100
)
1101-
# this is equivalent to self._values[key] = value
1102-
self._mgr.setitem_inplace(key, value)
1101+
# can't use _mgr.setitem_inplace yet bc could have *both*
1102+
# KeyError and then ValueError, xref GH#45070
1103+
self._set_values(key, value)
11031104
else:
11041105
# GH#12862 adding a new key to the Series
11051106
self.loc[key] = value

pandas/tests/series/indexing/test_setitem.py

+12-2
Original file line numberDiff line numberDiff line change
@@ -1350,15 +1350,25 @@ def test_6942(indexer_al):
13501350
assert df.iloc[0, 0] == t2
13511351

13521352

1353-
@pytest.mark.xfail(reason="Doesn't catch when numpy raises.")
1354-
def test_45070():
1353+
def test_setitem_positional_with_casting():
1354+
# GH#45070 case where in __setitem__ we get a KeyError, then when
1355+
# we fallback we *also* get a ValueError if we try to set inplace.
13551356
ser = Series([1, 2, 3], index=["a", "b", "c"])
13561357

13571358
ser[0] = "X"
13581359
expected = Series(["X", 2, 3], index=["a", "b", "c"], dtype=object)
13591360
tm.assert_series_equal(ser, expected)
13601361

13611362

1363+
def test_setitem_positional_float_into_int_coerces():
1364+
# Case where we hit a KeyError and then trying to set in-place incorrectly
1365+
# casts a float to an int
1366+
ser = Series([1, 2, 3], index=["a", "b", "c"])
1367+
ser[0] = 1.5
1368+
expected = Series([1.5, 2, 3], index=["a", "b", "c"])
1369+
tm.assert_series_equal(ser, expected)
1370+
1371+
13621372
@pytest.mark.xfail(reason="unwanted upcast")
13631373
def test_15231():
13641374
df = DataFrame([[1, 2], [3, 4]], columns=["a", "b"])

0 commit comments

Comments
 (0)