Skip to content

Backport PR #42644: BUG: KeyError when a series popped from data frame with bool indexer #42728

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
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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.3.2.rst
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ including other versions of pandas.
Fixed regressions
~~~~~~~~~~~~~~~~~
- Performance regression in :meth:`DataFrame.isin` and :meth:`Series.isin` for nullable data types (:issue:`42714`)
- Regression in updating values of :class:`pandas.Series` using boolean index, created by using :meth:`pandas.DataFrame.pop` (:issue:`42530`)
-
-

Expand Down
15 changes: 8 additions & 7 deletions pandas/core/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -1228,14 +1228,15 @@ def _maybe_update_cacher(
# a copy
if ref is None:
del self._cacher
elif len(self) == len(ref) and self.name in ref.columns:
# GH#42530 self.name must be in ref.columns
# to ensure column still in dataframe
# otherwise, either self or ref has swapped in new arrays
ref._maybe_cache_changed(cacher[0], self)
else:
if len(self) == len(ref):
# otherwise, either self or ref has swapped in new arrays
ref._maybe_cache_changed(cacher[0], self)
else:
# GH#33675 we have swapped in a new array, so parent
# reference to self is now invalid
ref._item_cache.pop(cacher[0], None)
# GH#33675 we have swapped in a new array, so parent
# reference to self is now invalid
ref._item_cache.pop(cacher[0], None)

super()._maybe_update_cacher(clear=clear, verify_is_copy=verify_is_copy)

Expand Down
15 changes: 15 additions & 0 deletions pandas/tests/series/indexing/test_setitem.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

from pandas import (
Categorical,
DataFrame,
DatetimeIndex,
Index,
MultiIndex,
Expand Down Expand Up @@ -906,3 +907,17 @@ def val(self):
def is_inplace(self, obj):
# This is specific to the 4 cases currently implemented for this class.
return obj.dtype.kind != "i"


def test_setitem_with_bool_indexer():
# GH#42530

df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
result = df.pop("b")
result[[True, False, False]] = 9
expected = Series(data=[9, 5, 6], name="b")
tm.assert_series_equal(result, expected)

df.loc[[True, False, False], "a"] = 10
expected = DataFrame({"a": [10, 2, 3]})
tm.assert_frame_equal(df, expected)