What is a generic way to slice a multi-indexed pandas dataframe along index and columns?
The documentation is dense and complete and worth reading (https://pandas.pydata.org/pandas-docs/stable/user_guide/advanced.html) and there are a number of answers on stack overflow that answer how to do it focused on 'rows' or columns (and this answer is quite thorough, Select rows in pandas MultiIndex DataFrame). But, I wanted a more straight forward answer that had examples addressing both at the same time.
creating the multiindex dataframe
cols_index = pd.MultiIndex.from_product([['a','b','c'],
['x','y','z']], names=['first','second'])
rows_index = pd.MultiIndex.from_product([['d','e','f'],
['u','v','w']], names=['third','fourth'])
df = pd.DataFrame(np.random.choice(10, (9,9)), index=rows_index, columns=cols_index)
df
Out[161]:
first a b
second c d c d
third e f e f e f e f
fourth fifth
j m 9 8 0 1 5 6 3 5
n 1 2 3 3 5 5 4 2
o 5 2 4 7 3 1 0 4
k m 6 6 3 3 4 4 1 7
n 0 6 0 9 2 3 7 5
o 7 8 0 9 7 8 3 4
l m 4 7 4 3 0 5 6 3
n 0 4 3 9 9 5 8 4
o 0 1 8 0 8 9 4 7
I would like to see examples that slice this along a combination of levels in the index and columns.