Skip to content

BUG: Series.__setitem__ positional raising ValueError #45232

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 8, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v1.5.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ Interval

Indexing
^^^^^^^^
-
- 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`)
-

Missing
Expand Down
5 changes: 3 additions & 2 deletions pandas/core/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -1098,8 +1098,9 @@ def __setitem__(self, key, value) -> None:
FutureWarning,
stacklevel=find_stack_level(),
)
# this is equivalent to self._values[key] = value
self._mgr.setitem_inplace(key, value)
# can't use _mgr.setitem_inplace yet bc could have *both*
# KeyError and then ValueError, xref GH#45070
self._set_values(key, value)
else:
# GH#12862 adding a new key to the Series
self.loc[key] = value
Expand Down
14 changes: 12 additions & 2 deletions pandas/tests/series/indexing/test_setitem.py
Original file line number Diff line number Diff line change
Expand Up @@ -1350,15 +1350,25 @@ def test_6942(indexer_al):
assert df.iloc[0, 0] == t2


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

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


def test_setitem_positional_float_into_int_coerces():
# Case where we hit a KeyError and then trying to set in-place incorrectly
# casts a float to an int
ser = Series([1, 2, 3], index=["a", "b", "c"])
ser[0] = 1.5
expected = Series([1.5, 2, 3], index=["a", "b", "c"])
tm.assert_series_equal(ser, expected)


@pytest.mark.xfail(reason="unwanted upcast")
def test_15231():
df = DataFrame([[1, 2], [3, 4]], columns=["a", "b"])
Expand Down