Skip to content Skip to sidebar Skip to footer

Selecting Sublevels Of Multiindex Columns In Pandas

I generate a multiindex dataframe like this example import pandas as pd import numpy as np iterables = [ ['co1', 'co2', 'co3', 'co4'], ['age','weight'] ] multi = pd.MultiIndex.fro

Solution 1:

IIUC then you can use loc and pass a tuple consisting of a slice and column label to access the col of interest at that level:

In [59]:
iterables = [ ['co1', 'co2', 'co3', 'co4'], ['age','weight'] ]
multi = pd.MultiIndex.from_product(iterables, names= ["Spread", "attribute"])
df = pd.DataFrame(np.random.rand(80).reshape(10,8),index = range(0,10), columns = multi)
df

Out[59]:
Spread          co1                 co2                 co3            \
attribute       age    weight       age    weight       age    weight   
00.6009470.5095370.6055380.4960020.2152060.07507910.1529560.9228320.1677880.0247610.6223780.98303020.7124780.6037980.4070140.6254740.4455920.90324030.4205690.5766040.2200970.4016240.9294640.51202640.2730880.0323030.6075770.8362310.7518450.18152250.8596990.2747600.4568120.6661090.3499610.23789460.6327540.6032520.1574160.2215760.0683550.12186470.0905950.0355260.6982620.5257700.7926180.22060180.6702360.8051950.3106800.1004640.8752990.85323890.0205010.4052450.4476140.9993400.6596160.709312   

Spread          co4            
attribute       age    weight  
00.2974210.41573010.2352590.15601420.3657620.19829930.6954310.47845740.3316570.33843650.9438100.09799960.6387200.03374770.6469690.47531680.6232250.02497690.0234940.959514  

In [61]:
df.loc[1,(slice(None),'weight')]

Out[61]:
Spread  attribute
co1     weight       0.922832
co2     weight       0.024761
co3     weight       0.983030
co4     weight       0.156014
Name: 1, dtype: float64

To explain the syntax:

df.loc[1,(slice(None),'weight')]

So the first param is just your index lave, the second param is a tuple consisting of a slice and a col label, the first member being slice(None) selects all cols 'col1' to 'col4' in effect, then the second param selects at the next level cols that match the label 'weight'

Post a Comment for "Selecting Sublevels Of Multiindex Columns In Pandas"