Using pandas.Grouper for multiple columns in MultiIndex

3,932 views
Skip to first unread message

Kent Maxwell

unread,
Feb 8, 2018, 9:54:59 AM2/8/18
to PyData
Hello,

I am trying to use the pandas.Grouper to groupby two different values in a MultiIndex and I can't seem to figure it out.  

Consider this example:
import pandas as pd


values
= [['2017-01-15', 'Tim', 4],
         
['2016-06-17', 'Tim', 3],
         
['2018-04-02', 'Tim', 2],
         
['2017-01-15', 'Sue', 4],
         
['2016-06-17', 'Sue', 3],
         
['2018-04-02', 'Sue', 2],
         
['2017-01-15', 'Eric', 4],
         
['2016-06-17', 'Eric', 3],
         
['2018-04-02', 'Betty', 2],
         
['2017-01-15', 'Betty', 4],
         
['2016-06-17', 'Betty', 3],
         
['2018-01-02', 'Betty', 2]]


df
= pd.DataFrame(values)
# Convert first column to datetime
df
[0] = df[0].astype('datetime64[ns]')
# Set first two columns as index
df
= df.set_index([0, 1])


# Group by Year
df
.groupby(pd.Grouper(level=0, freq='Y')).sum()
# Group by Person
df
.groupby(pd.Grouper(level=1)).sum()
# Group by Year, Person
df
.groupby(pd.Grouper(level=0, freq='Y'), pd.Grouper(level=1)).sum()
# ValueError: No axis named Grouper(level=1, axis=0, sort=False) for object type <class 'pandas.core.frame.DataFrame'>

The first two statements that use Grouper work as expected.  However, when I try to combine them I get an error.  I do not understand why this doesn't work.  Even further, I do not understand what I need to do to achieve the result I am looking for.

Thanks,

Kent

Paul Hobson

unread,
Feb 8, 2018, 10:49:16 AM2/8/18
to pyd...@googlegroups.com
I think you need to put them in a list:
df.groupby(by=[pd.Grouper(level=0, freq='Y'), pd.Grouper(level=1)]).sum()


--
You received this message because you are subscribed to the Google Groups "PyData" group.
To unsubscribe from this group and stop receiving emails from it, send an email to pydata+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Kent Maxwell

unread,
Feb 12, 2018, 10:34:36 AM2/12/18
to pyd...@googlegroups.com
Hello Paul,

Thank you!  I appreciate this response.  This works as expected!

Kent
Reply all
Reply to author
Forward
0 new messages