How to use pandas Grouper on multiple keys?

Viewed 10617

I need to groupby-transform a dataframe by a datetime column AND another str(object) column to apply a function by group and asign the result to each of the row members of the group. I understand the groupby workflow but cannot make a pandas.Grouper for both conditions at the same time. Thus:

How to use pandas.Grouper on multiple columns?

2 Answers

Use the DataFrame.groupby with a list of pandas.Grouper as the by argument like this:

df['result'] = df.groupby([
                 pd.Grouper('dt', freq='D'),
                 pd.Grouper('other_column')
               ]).transform(foo)

If your second column is a non-datetime series, you can group it with a date-time column like this:

df['res'] = df.groupby([
                 pd.Grouper('dt', freq='D'),
                 'other_column'
               ]).transform(foo)

Note that in this case you don't have to use pd.Grouper for second column beacuse its a string object and not a time object. pd.Grouper is only compatible with datetime columns.

Related