Skip to content

BUG: broadcasting listlike values in Series.__setitem__ GH#44265 #44275

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 9 commits into from
Nov 5, 2021
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.4.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -540,6 +540,7 @@ Indexing
- Bug in setting a scalar :class:`Interval` value into a :class:`Series` with ``IntervalDtype`` when the scalar's sides are floats and the values' sides are integers (:issue:`44201`)
- Bug when setting string-backed :class:`Categorical` values that can be parsed to datetimes into a :class:`DatetimeArray` or :class:`Series` or :class:`DataFrame` column backed by :class:`DatetimeArray` failing to parse these strings (:issue:`44236`)
- Bug in :meth:`Series.__setitem__` with an integer dtype other than ``int64`` setting with a ``range`` object unnecessarily upcasting to ``int64`` (:issue:`44261`)
- Bug in :meth:`Series.__setitem__` with a boolean mask indexer setting a listlike value of length 1 incorrectly broadcasting that value (:issue:`44265`)
-

Missing
Expand Down
17 changes: 17 additions & 0 deletions pandas/core/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -1096,9 +1096,26 @@ def __setitem__(self, key, value) -> None:
if com.is_bool_indexer(key):
key = check_bool_indexer(self.index, key)
key = np.asarray(key, dtype=bool)

if (
is_list_like(value)
and len(value) != len(self)
and not isinstance(value, Series)
and not is_object_dtype(self.dtype)
):
# Series will be reindexed to have matching length inside
# _where call below
# GH#44265
indexer = key.nonzero()[0]
self._set_values(indexer, value)
return

# otherwise with listlike other we interpret series[mask] = other
# as series[mask] = other[mask]
try:
self._where(~key, value, inplace=True)
except InvalidIndexError:
# test_where_dups
self.iloc[key] = value
return

Expand Down
22 changes: 15 additions & 7 deletions pandas/tests/series/indexing/test_where.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ def test_where_unsafe():
s = Series(np.arange(10))
mask = s > 5

msg = "cannot assign mismatch length to masked array"
msg = "cannot set using a list-like indexer with a different length than the value"
with pytest.raises(ValueError, match=msg):
s[mask] = [5, 4, 3, 2, 1]

Expand Down Expand Up @@ -161,13 +161,10 @@ def test_where_error():
tm.assert_series_equal(s, expected)

# failures
msg = "cannot assign mismatch length to masked array"
msg = "cannot set using a list-like indexer with a different length than the value"
with pytest.raises(ValueError, match=msg):
s[[True, False]] = [0, 2, 3]
msg = (
"NumPy boolean array indexing assignment cannot assign 0 input "
"values to the 1 output values where the mask is true"
)

with pytest.raises(ValueError, match=msg):
s[[True, False]] = []

Expand Down Expand Up @@ -298,6 +295,7 @@ def test_where_setitem_invalid():
"box", [lambda x: np.array([x]), lambda x: [x], lambda x: (x,)]
)
def test_broadcast(size, mask, item, box):
# GH#8801, GH#4195
selection = np.resize(mask, size)

data = np.arange(size, dtype=float)
Expand All @@ -309,7 +307,17 @@ def test_broadcast(size, mask, item, box):
)

s = Series(data)
s[selection] = box(item)

if selection.sum() != 1:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hmm maybe make this another test

it's really confusing u r boxing first then setting it after

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sure, updated

msg = (
"cannot set using a list-like indexer with a different "
"length than the value"
)
with pytest.raises(ValueError, match=msg):
# GH#44265
s[selection] = box(item)

s[selection] = item
tm.assert_series_equal(s, expected)

s = Series(data)
Expand Down