Skip to content

Commit 90bd817

Browse files
committed
BUG: KeyError when a series popped from data frame with bool indexer (#42644)
1 parent 85b7375 commit 90bd817

File tree

3 files changed

+24
-8
lines changed

3 files changed

+24
-8
lines changed

doc/source/whatsnew/v1.4.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -225,7 +225,7 @@ Indexing
225225
- Bug in :meth:`Series.loc` when with a :class:`MultiIndex` whose first level contains only ``np.nan`` values (:issue:`42055`)
226226
- Bug in indexing on a :class:`Series` or :class:`DataFrame` with a :class:`DatetimeIndex` when passing a string, the return type depended on whether the index was monotonic (:issue:`24892`)
227227
- Bug in indexing on a :class:`MultiIndex` failing to drop scalar levels when the indexer is a tuple containing a datetime-like string (:issue:`42476`)
228-
-
228+
- Bug in updating values of :class:`pandas.Series` using boolean index, created by using :meth:`pandas.DataFrame.pop` (:issue:`42530`)
229229

230230
Missing
231231
^^^^^^^

pandas/core/series.py

+8-7
Original file line numberDiff line numberDiff line change
@@ -1233,14 +1233,15 @@ def _maybe_update_cacher(
12331233
# a copy
12341234
if ref is None:
12351235
del self._cacher
1236+
elif len(self) == len(ref) and self.name in ref.columns:
1237+
# GH#42530 self.name must be in ref.columns
1238+
# to ensure column still in dataframe
1239+
# otherwise, either self or ref has swapped in new arrays
1240+
ref._maybe_cache_changed(cacher[0], self)
12361241
else:
1237-
if len(self) == len(ref):
1238-
# otherwise, either self or ref has swapped in new arrays
1239-
ref._maybe_cache_changed(cacher[0], self)
1240-
else:
1241-
# GH#33675 we have swapped in a new array, so parent
1242-
# reference to self is now invalid
1243-
ref._item_cache.pop(cacher[0], None)
1242+
# GH#33675 we have swapped in a new array, so parent
1243+
# reference to self is now invalid
1244+
ref._item_cache.pop(cacher[0], None)
12441245

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

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
IntervalIndex,
@@ -945,3 +946,17 @@ def test_setitem_int_as_positional_fallback_deprecation():
945946
with tm.assert_produces_warning(FutureWarning, match=msg):
946947
ser3[4] = 99
947948
tm.assert_series_equal(ser3, expected3)
949+
950+
951+
def test_setitem_with_bool_indexer():
952+
# GH#42530
953+
954+
df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
955+
result = df.pop("b")
956+
result[[True, False, False]] = 9
957+
expected = Series(data=[9, 5, 6], name="b")
958+
tm.assert_series_equal(result, expected)
959+
960+
df.loc[[True, False, False], "a"] = 10
961+
expected = DataFrame({"a": [10, 2, 3]})
962+
tm.assert_frame_equal(df, expected)

0 commit comments

Comments
 (0)