Last active
May 11, 2020 15:57
-
-
Save afrendeiro/a2a3b39133ab68963559ac33ff448c91 to your computer and use it in GitHub Desktop.
Easier access to pandas.MultiIndex values circumventing get_level_values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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