jhconning
5/6/2017 - 3:00 AM

pandas multiindex and groupby

pandas multiindex and groupby

# to create a multinindex

df.sort_values(by = ['Year', 'UnitDesc','bin'], inplace = True)
df = df.set_index(['Year', 'UnitDesc','bin'],drop = False)

# To turn one level of the index into a column
df = df.unstack('UnitDesc')['Value']
df.head()

# to pull out all data in level='Year' 
df.ix[2007]

#to use groupby operations on a multiindex dataframe refer to 'levels' rather than column names

df.index.names   # will give you label names
grouped = df.groupby(level=['Year'])     

#to loop through and unpack groups
for (yr, bn), group in df.groupby(level=['Year','bin']):
    print(yr,bn)
    print(group)