Skip to content

Commit a23c736

Browse files
committed
BUG: iloc fails with non lex-sorted MultiIndex #13797
added comments and modified test code
1 parent 072d2a3 commit a23c736

File tree

2 files changed

+26
-16
lines changed

2 files changed

+26
-16
lines changed

pandas/core/indexing.py

+2
Original file line numberDiff line numberDiff line change
@@ -903,6 +903,8 @@ def _getitem_lowerdim(self, tup):
903903

904904
# we maybe be using a tuple to represent multiple dimensions here
905905
ax0 = self.obj._get_axis(0)
906+
# ...but iloc should handle the tuple as simple integer-location
907+
# instead of checking it as multiindex representation (GH 13797)
906908
if isinstance(ax0, MultiIndex) and self.name != 'iloc':
907909
result = self._handle_lowerdim_multi_index_axis0(tup)
908910
if result is not None:

pandas/tests/test_multilevel.py

+24-16
Original file line numberDiff line numberDiff line change
@@ -2422,22 +2422,30 @@ def test_repeat(self):
24222422

24232423
def test_iloc_mi(self):
24242424
# GH 13797
2425-
2426-
ind_nonLex = [
2427-
['CC', 'CC', 'CC', 'BB', 'BB'],
2428-
['A', 'B', 'B', 'a', 'b']
2429-
]
2430-
2431-
strCol = pd.DataFrame(
2432-
['fooA', 'fooB', 'fooC', 'fooD', 'fooE'])
2433-
2434-
dat = np.arange(1, 26).reshape(5, 5)
2435-
df = pd.concat([strCol, pd.DataFrame(dat)], axis=1)
2436-
df1 = pd.DataFrame(df.values, index=ind_nonLex)
2437-
2438-
assert df1.iloc[0, 0] == 'fooA'
2439-
assert df1.iloc[4, 0] == 'fooE'
2440-
assert df1.iloc[4, 5] == 25
2425+
# Test if iloc can handle integer locations in MultiIndexed DataFrame
2426+
2427+
data =[
2428+
['str00', 'str01'],
2429+
['str10', 'str11'],
2430+
['str20', 'srt21'],
2431+
['str30', 'str31'],
2432+
['str40', 'str41']
2433+
]
2434+
2435+
mi= pd.MultiIndex.from_tuples(
2436+
[('CC','A'),
2437+
('CC','B'),
2438+
('CC','B'),
2439+
('BB','a'),
2440+
('BB','b')
2441+
])
2442+
2443+
ans = pd.DataFrame(data)
2444+
df_mi = pd.DataFrame(data, index = mi)
2445+
2446+
res = pd.DataFrame([[df_mi.iloc[r,c] for c in range(2)] for r in range(5)])
2447+
2448+
assert_frame_equal(res, ans)
24412449

24422450

24432451
if __name__ == '__main__':

0 commit comments

Comments
 (0)