Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Easier access to pandas.MultiIndex values circumventing get_level_values
import pandas as pd
import seaborn as sns
class Loc:
def __init__(self, pandas_obj):
self._obj = pandas_obj
def __getitem__(self, x):
return pd.Index(self._obj.index.to_frame().loc[x])
class ILoc:
def __init__(self, pandas_obj):
self._obj = pandas_obj
def __getitem__(self, x):
return pd.Index(self._obj.index.to_frame().iloc[x])
@pd.api.extensions.register_dataframe_accessor("mindex")
class MultiIndexAccessor:
def __init__(self, pandas_obj):
self._obj = pandas_obj
self.loc = Loc(self._obj)
self.iloc = ILoc(self._obj)
def __getitem__(self, x):
assert isinstance(x, (int, str))
return self._obj.index.get_level_values(x)
df = sns.load_dataset("fmri").set_index(['event', 'region'])
assert (df.mindex['region'] == df.mindex.loc[:, "region"]).all()
assert (df.mindex['region'] == df.mindex.iloc[:, 1]).all()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment