Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jhconning/22faf25a9203c3c592caf7eb07f866fc to your computer and use it in GitHub Desktop.
Save jhconning/22faf25a9203c3c592caf7eb07f866fc to your computer and use it in GitHub Desktop.
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment