Skip to content

Commit 406e12f

Browse files
Backport PR pandas-dev#31631: REGR: Fixed setitem with MultiIndex (pandas-dev#31637)
Co-authored-by: Tom Augspurger <[email protected]>
1 parent 5c80b35 commit 406e12f

File tree

3 files changed

+13
-1
lines changed

3 files changed

+13
-1
lines changed

doc/source/whatsnew/v1.0.1.rst

+1
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ Fixed regressions
1717

1818
- Fixed regression in :class:`DataFrame` setting values with a slice (e.g. ``df[-4:] = 1``) indexing by label instead of position (:issue:`31469`)
1919
- Fixed regression when indexing a ``Series`` or ``DataFrame`` indexed by ``DatetimeIndex`` with a slice containg a :class:`datetime.date` (:issue:`31501`)
20+
- Fixed regression in ``DataFrame.__setitem__`` raising an ``AttributeError`` with a :class:`MultiIndex` and a non-monotonic indexer (:issue:`31449`)
2021
- Fixed regression in :class:`Series` multiplication when multiplying a numeric :class:`Series` with >10000 elements with a timedelta-like scalar (:issue:`31457`)
2122
- Fixed regression in :meth:`GroupBy.apply` if called with a function which returned a non-pandas non-scalar object (e.g. a list or numpy array) (:issue:`31441`)
2223
- Fixed regression in :meth:`to_datetime` when parsing non-nanosecond resolution datetimes (:issue:`31491`)

pandas/core/indexing.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -926,7 +926,8 @@ def _setitem_with_indexer(self, indexer, value):
926926

927927
# we can directly set the series here
928928
# as we select a slice indexer on the mi
929-
idx = index._convert_slice_indexer(idx)
929+
if isinstance(idx, slice):
930+
idx = index._convert_slice_indexer(idx)
930931
obj._consolidate_inplace()
931932
obj = obj.copy()
932933
obj._data = obj._data.setitem(indexer=tuple([idx]), value=value)

pandas/tests/indexing/multiindex/test_setitem.py

+10
Original file line numberDiff line numberDiff line change
@@ -414,6 +414,16 @@ def test_astype_assignment_with_dups(self):
414414
df["A"] = df["A"].astype(np.float64)
415415
tm.assert_index_equal(df.index, index)
416416

417+
def test_setitem_nonmonotonic(self):
418+
# https://github.com/pandas-dev/pandas/issues/31449
419+
index = pd.MultiIndex.from_tuples(
420+
[("a", "c"), ("b", "x"), ("a", "d")], names=["l1", "l2"]
421+
)
422+
df = pd.DataFrame(data=[0, 1, 2], index=index, columns=["e"])
423+
df.loc["a", "e"] = np.arange(99, 101, dtype="int64")
424+
expected = pd.DataFrame({"e": [99, 1, 100]}, index=index)
425+
tm.assert_frame_equal(df, expected)
426+
417427

418428
def test_frame_setitem_view_direct(multiindex_dataframe_random_data):
419429
# this works because we are modifying the underlying array

0 commit comments

Comments
 (0)