How to use pandas Grouper on multiple keys?

2019-06-10 07:28发布

问题:

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?

回答1:

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)