Skip to content

Commit fe87624

Browse files
authored
BUG: loc.setitem corner case (#37931)
* BUG: loc.setitem corner case * flesh out comment
1 parent fa999f3 commit fe87624

File tree

2 files changed

+14
-1
lines changed

2 files changed

+14
-1
lines changed

pandas/core/indexing.py

+8-1
Original file line numberDiff line numberDiff line change
@@ -1649,7 +1649,8 @@ def _setitem_with_indexer_split_path(self, indexer, value, name: str):
16491649
value = self._align_series(indexer, value)
16501650

16511651
# Ensure we have something we can iterate over
1652-
ilocs = self._ensure_iterable_column_indexer(indexer[1])
1652+
info_axis = indexer[1]
1653+
ilocs = self._ensure_iterable_column_indexer(info_axis)
16531654

16541655
pi = indexer[0]
16551656
lplane_indexer = length_of_indexer(pi, self.obj.index)
@@ -1673,6 +1674,12 @@ def _setitem_with_indexer_split_path(self, indexer, value, name: str):
16731674
# We are trying to set N values into M entries of a single
16741675
# column, which is invalid for N != M
16751676
# Exclude zero-len for e.g. boolean masking that is all-false
1677+
1678+
if len(value) == 1 and not is_integer(info_axis):
1679+
# This is a case like df.iloc[:3, [1]] = [0]
1680+
# where we treat as df.iloc[:3, 1] = 0
1681+
return self._setitem_with_indexer((pi, info_axis[0]), value[0])
1682+
16761683
raise ValueError(
16771684
"Must have equal len keys and value "
16781685
"when setting with an iterable"

pandas/tests/indexing/multiindex/test_setitem.py

+6
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,12 @@ def test_multiindex_assignment(self):
210210
with pytest.raises(ValueError, match=msg):
211211
df.loc[4, "c"] = [0]
212212

213+
# But with a length-1 listlike column indexer this behaves like
214+
# `df.loc[4, "c"] = 0
215+
df.loc[4, ["c"]] = [0]
216+
assert (df.loc[4, "c"] == 0).all()
217+
218+
def test_groupby_example(self):
213219
# groupby example
214220
NUM_ROWS = 100
215221
NUM_COLS = 10

0 commit comments

Comments
 (0)