Search code examples
pythonpandaspandas-groupby

Python Pandas groupby based on another dataframe


I have two dataframes with a common index. I would like to group df1 based on a subset of columns in df2.

I know how to groupby multiple columns already in df1, like df1.groupby(['col1', 'col2']) and I know how to group on a different series with the same index, like df1.groupby(df2['col1']). Is there an immediate way to do something like

>>> df1.groupby(df[['col1', 'col2']])
# ValueError: Grouper for '<class 'pandas.core.frame.DataFrame'>' not 1-dimensional

Of course, I could do

df1.groupby([df2['col1'], df2['col2']])

but it seems there should be a more direct syntax for this. (Imagine having several grouping columns, etc.)


Solution

  • How about:

    gbobj = pd.concat([df1, df2[['col1','col2']], axis=1).groupby(['col1','col2'])