Skip to content

Commit 74dad82

Browse files
authored
BUG: iloc setitem with 3d indexer not raising (#31813)
1 parent 46a77f6 commit 74dad82

File tree

3 files changed

+23
-30
lines changed

3 files changed

+23
-30
lines changed

pandas/core/internals/blocks.py

+3
Original file line numberDiff line numberDiff line change
@@ -830,6 +830,9 @@ def setitem(self, indexer, value):
830830
"""
831831
transpose = self.ndim == 2
832832

833+
if isinstance(indexer, np.ndarray) and indexer.ndim > self.ndim:
834+
raise ValueError(f"Cannot set values with ndim > {self.ndim}")
835+
833836
# coerce None values, if appropriate
834837
if value is None:
835838
if self.is_numeric:

pandas/io/stata.py

+4
Original file line numberDiff line numberDiff line change
@@ -1678,6 +1678,10 @@ def _do_convert_missing(self, data: DataFrame, convert_missing: bool) -> DataFra
16781678
missing_value = StataMissingValue(um)
16791679

16801680
loc = missing_loc[umissing_loc == j]
1681+
if loc.ndim == 2 and loc.shape[1] == 1:
1682+
# GH#31813 avoid trying to set Series values with wrong
1683+
# dimension
1684+
loc = loc[:, 0]
16811685
replacement.iloc[loc] = missing_value
16821686
else: # All replacements are identical
16831687
dtype = series.dtype

pandas/tests/indexing/test_indexing.py

+16-30
Original file line numberDiff line numberDiff line change
@@ -133,38 +133,24 @@ def test_setitem_ndarray_3d(self, index, obj, idxr, idxr_id):
133133
idxr = idxr(obj)
134134
nd3 = np.random.randint(5, size=(2, 2, 2))
135135

136-
msg = (
137-
r"Buffer has wrong number of dimensions \(expected 1, "
138-
r"got 3\)|"
139-
"'pandas._libs.interval.IntervalTree' object has no attribute "
140-
"'get_loc'|" # AttributeError
141-
"unhashable type: 'numpy.ndarray'|" # TypeError
142-
"No matching signature found|" # TypeError
143-
r"^\[\[\[|" # pandas.core.indexing.IndexingError
144-
"Index data must be 1-dimensional"
145-
)
146-
147-
if (idxr_id == "iloc") or (
148-
(
149-
isinstance(obj, Series)
150-
and idxr_id == "setitem"
151-
and index.inferred_type
152-
in [
153-
"floating",
154-
"string",
155-
"datetime64",
156-
"period",
157-
"timedelta64",
158-
"boolean",
159-
"categorical",
160-
]
161-
)
136+
if idxr_id == "iloc":
137+
err = ValueError
138+
msg = f"Cannot set values with ndim > {obj.ndim}"
139+
elif (
140+
isinstance(index, pd.IntervalIndex)
141+
and idxr_id == "setitem"
142+
and obj.ndim == 1
162143
):
163-
idxr[nd3] = 0
144+
err = AttributeError
145+
msg = (
146+
"'pandas._libs.interval.IntervalTree' object has no attribute 'get_loc'"
147+
)
164148
else:
165-
err = (ValueError, AttributeError)
166-
with pytest.raises(err, match=msg):
167-
idxr[nd3] = 0
149+
err = ValueError
150+
msg = r"Buffer has wrong number of dimensions \(expected 1, got 3\)|"
151+
152+
with pytest.raises(err, match=msg):
153+
idxr[nd3] = 0
168154

169155
def test_inf_upcast(self):
170156
# GH 16957

0 commit comments

Comments
 (0)