When indexing a MultiIndex-ed DataFrame, it seems like .iloc assumes you're referencing the "inner level" of the index while .loc looks at the outer level.
For example:
np.random.seed(123)
iterables = [['bar', 'baz', 'foo', 'qux'], ['one', 'two']]
idx = pd.MultiIndex.from_product(iterables, names=['first', 'second'])
df = pd.DataFrame(np.random.randn(8, 4), index=idx)
# .loc looks at the outer index:
print(df.loc['qux'])
# df.loc['two'] would throw KeyError
0 1 2 3
second
one -1.25388 -0.63775 0.90711 -1.42868
two -0.14007 -0.86175 -0.25562 -2.79859
# while .iloc looks at the inner index:
print(df.iloc[-1])
0 -0.14007
1 -0.86175
2 -0.25562
3 -2.79859
Name: (qux, two), dtype: float64
Two questions:
Firstly, why is this? Is it a deliberate design decision?
Secondly, can I use .iloc to reference the outer level of the index, to yield the result below? I'm aware I could first find the last member of the index with get_level_values and then .loc-index with that, but wandering if it can be done more directly, either with funky .iloc syntax or some existing function designed specifically for the case.
# df.iloc[-1]
qux one 0.89071 1.75489 1.49564 1.06939
two -0.77271 0.79486 0.31427 -1.32627
-1actually consists of two values:Name: (qux, two). It's more thatlocallows referencing a full index (e.g.df.loc['qux', 'two']) or a partial one, but it is in order. you could do areset_indexand set the index in the other order if you wanted to. - Corley Brigman