What is the simplest syntax to index into a pandas.MultiIndex object and keep the level names? The square bracket operator [] produces tuples with level names dropped. I am looking for the cleanest way to write the last line in the code below (ideally something like index.iloc[0]).
import pandas as pd
index = pd.MultiIndex.from_product([[2013, 2014], [1, 2]],
names=['year', 'visit'])
print(index)
print(index[0]) # tuples with level names dropped
print(pd.MultiIndex.from_tuples([index[0]],names=index.names)) # force reconstruct with level names
Produces output:
MultiIndex([(2013, 1),
(2013, 2),
(2014, 1),
(2014, 2)],
names=['year', 'visit'])
(2013, 1)
MultiIndex([(2013, 1)],
names=['year', 'visit'])