Created
May 6, 2017 03:00
-
-
Save jhconning/22faf25a9203c3c592caf7eb07f866fc to your computer and use it in GitHub Desktop.
pandas multiindex and groupby
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
# 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