Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save karpanGit/08bc291fa67c60c6fa4a6686849388dc to your computer and use it in GitHub Desktop.

Select an option

Save karpanGit/08bc291fa67c60c6fa4a6686849388dc to your computer and use it in GitHub Desktop.
pandas, multi index, select with cross section or index slice
import pandas as pd
import numpy as np
# create a dataset with multi indices for both both index and columns
def indx_names(prefix: str, num: int):
return [f'{prefix}{_:_>2}' for _ in range(num)]
idx = pd.MultiIndex.from_product([indx_names('A',4), indx_names('B',2), indx_names('C',4), indx_names('D',2)])
cols = pd.MultiIndex.from_tuples([('a', 'foo'), ('a', 'bar'), ('b', 'foo'), ('b', 'bah')], names=['lvl0', 'lvl1'])
df = pd.DataFrame(np.arange(len(idx)*len(cols)).reshape(len(idx), len(cols)), index=idx, columns=cols)
# using cross section, dropping level
res = df.xs('A_3', level=0, axis='index')
# using cross section, without dropping level
res = df.xs('A_3', level=0, axis='index', drop_level=False)
# using index slice, dropping level
from pandas import IndexSlice
idx = IndexSlice
res = df.loc[idx['A_3',:,:,:], :]
res.index = res.index.droplevel(0)
# using cross section, multiple levels, dropping level
res = df.xs(('A_3', 'C_1'), level=[0, 2], axis='index')
# using index slice, dropping level
res = df.loc[idx['A_3', :, ['C_1'],:],:]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment