Skip to content

Commit 68c51c5

Browse files
committed
BUG: Fix strange behaviour of Series.iloc on MultiIndex Series (#17148)
1 parent 95f4f7d commit 68c51c5

File tree

3 files changed

+37
-1
lines changed

3 files changed

+37
-1
lines changed

doc/source/whatsnew/v0.21.0.txt

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

333334
I/O
334335
^^^

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 not is_integer(key):
150151
try:
151152
return axis.get_loc(key)
152153
except Exception:

pandas/tests/indexing/test_iloc.py

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

272+
def test_iloc_setitem_int_multiindex_series(self):
273+
# GH17148
274+
def check_scenario(data, indexes, values, expected_k):
275+
df = pd.DataFrame(
276+
data=data,
277+
columns=['i', 'j', 'k'])
278+
df.set_index(['i', 'j'], inplace=True)
279+
280+
series = df.k.copy()
281+
for i, v in zip(indexes, values):
282+
series.iloc[i] += v
283+
284+
df.k = expected_k
285+
expected = df.k.copy()
286+
tm.assert_series_equal(series, expected)
287+
288+
check_scenario(
289+
data=[[1, 22, 5], [1, 33, 6]],
290+
indexes=[0, -1, 1],
291+
values=[2, 3, 1],
292+
expected_k=[7, 10])
293+
294+
check_scenario(
295+
data=[[1, 3, 7], [2, 4, 8]],
296+
indexes=[0, -1, 1],
297+
values=[1, 1, 10],
298+
expected_k=[8, 19])
299+
300+
check_scenario(
301+
data=[[1, 11, 4], [2, 22, 5], [3, 33, 6]],
302+
indexes=[0, -1, 1],
303+
values=[4, 7, 10],
304+
expected_k=[8, 15, 13])
305+
272306
def test_iloc_setitem_list(self):
273307

274308
# setitem with an iloc list

0 commit comments

Comments
 (0)