Skip to content

Commit 2bec750

Browse files
ante328jreback
ante328
authored andcommitted
BUG: Fix strange behaviour of Series.iloc on MultiIndex Series (#17148) (#17291)
1 parent dfaf8c6 commit 2bec750

File tree

3 files changed

+32
-1
lines changed

3 files changed

+32
-1
lines changed

doc/source/whatsnew/v0.21.0.txt

+1
Original file line numberDiff line numberDiff line change
@@ -353,6 +353,7 @@ Indexing
353353
- Fixes ``DataFrame.loc`` for setting with alignment and tz-aware ``DatetimeIndex`` (:issue:`16889`)
354354
- Avoids ``IndexError`` when passing an Index or Series to ``.iloc`` with older numpy (:issue:`17193`)
355355
- Allow unicode empty strings as placeholders in multilevel columns in Python 2 (:issue:`17099`)
356+
- Bug in ``.iloc`` when used with inplace addition or assignment and an int indexer on a ``MultiIndex`` causing the wrong indexes to be read from and written to (:issue:`17148`)
356357

357358
I/O
358359
^^^

pandas/core/indexing.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,8 @@ def _get_setitem_indexer(self, key):
146146
return self._convert_tuple(key, is_setter=True)
147147

148148
axis = self.obj._get_axis(0)
149-
if isinstance(axis, MultiIndex):
149+
150+
if isinstance(axis, MultiIndex) and self.name != 'iloc':
150151
try:
151152
return axis.get_loc(key)
152153
except Exception:

pandas/tests/indexing/test_iloc.py

+29
Original file line numberDiff line numberDiff line change
@@ -269,6 +269,35 @@ def test_iloc_setitem(self):
269269
expected = Series([0, 1, 0], index=[4, 5, 6])
270270
tm.assert_series_equal(s, expected)
271271

272+
@pytest.mark.parametrize(
273+
'data, indexes, values, expected_k', [
274+
# test without indexer value in first level of MultiIndex
275+
([[2, 22, 5], [2, 33, 6]], [0, -1, 1], [2, 3, 1], [7, 10]),
276+
# test like code sample 1 in the issue
277+
([[1, 22, 555], [1, 33, 666]], [0, -1, 1], [200, 300, 100],
278+
[755, 1066]),
279+
# test like code sample 2 in the issue
280+
([[1, 3, 7], [2, 4, 8]], [0, -1, 1], [10, 10, 1000], [17, 1018]),
281+
# test like code sample 3 in the issue
282+
([[1, 11, 4], [2, 22, 5], [3, 33, 6]], [0, -1, 1], [4, 7, 10],
283+
[8, 15, 13])
284+
])
285+
def test_iloc_setitem_int_multiindex_series(
286+
self, data, indexes, values, expected_k):
287+
# GH17148
288+
df = pd.DataFrame(
289+
data=data,
290+
columns=['i', 'j', 'k'])
291+
df = df.set_index(['i', 'j'])
292+
293+
series = df.k.copy()
294+
for i, v in zip(indexes, values):
295+
series.iloc[i] += v
296+
297+
df['k'] = expected_k
298+
expected = df.k
299+
tm.assert_series_equal(series, expected)
300+
272301
def test_iloc_setitem_list(self):
273302

274303
# setitem with an iloc list

0 commit comments

Comments
 (0)