Skip to content

Commit 3f32083

Browse files
Backport PR #42644: BUG: KeyError when a series popped from data frame with bool indexer (#42728)
Co-authored-by: Shoham Debnath <[email protected]>
1 parent 862a871 commit 3f32083

File tree

3 files changed

+24
-7
lines changed

3 files changed

+24
-7
lines changed

doc/source/whatsnew/v1.3.2.rst

+1
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ including other versions of pandas.
1515
Fixed regressions
1616
~~~~~~~~~~~~~~~~~
1717
- Performance regression in :meth:`DataFrame.isin` and :meth:`Series.isin` for nullable data types (:issue:`42714`)
18+
- Regression in updating values of :class:`pandas.Series` using boolean index, created by using :meth:`pandas.DataFrame.pop` (:issue:`42530`)
1819
-
1920
-
2021

pandas/core/series.py

+8-7
Original file line numberDiff line numberDiff line change
@@ -1228,14 +1228,15 @@ def _maybe_update_cacher(
12281228
# a copy
12291229
if ref is None:
12301230
del self._cacher
1231+
elif len(self) == len(ref) and self.name in ref.columns:
1232+
# GH#42530 self.name must be in ref.columns
1233+
# to ensure column still in dataframe
1234+
# otherwise, either self or ref has swapped in new arrays
1235+
ref._maybe_cache_changed(cacher[0], self)
12311236
else:
1232-
if len(self) == len(ref):
1233-
# otherwise, either self or ref has swapped in new arrays
1234-
ref._maybe_cache_changed(cacher[0], self)
1235-
else:
1236-
# GH#33675 we have swapped in a new array, so parent
1237-
# reference to self is now invalid
1238-
ref._item_cache.pop(cacher[0], None)
1237+
# GH#33675 we have swapped in a new array, so parent
1238+
# reference to self is now invalid
1239+
ref._item_cache.pop(cacher[0], None)
12391240

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

pandas/tests/series/indexing/test_setitem.py

+15
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88

99
from pandas import (
1010
Categorical,
11+
DataFrame,
1112
DatetimeIndex,
1213
Index,
1314
MultiIndex,
@@ -906,3 +907,17 @@ def val(self):
906907
def is_inplace(self, obj):
907908
# This is specific to the 4 cases currently implemented for this class.
908909
return obj.dtype.kind != "i"
910+
911+
912+
def test_setitem_with_bool_indexer():
913+
# GH#42530
914+
915+
df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
916+
result = df.pop("b")
917+
result[[True, False, False]] = 9
918+
expected = Series(data=[9, 5, 6], name="b")
919+
tm.assert_series_equal(result, expected)
920+
921+
df.loc[[True, False, False], "a"] = 10
922+
expected = DataFrame({"a": [10, 2, 3]})
923+
tm.assert_frame_equal(df, expected)

0 commit comments

Comments
 (0)