Groupby multiindex columns using dictionary

One way is to pass a function to groupby, and then convert the tuples back to MultiIndex

out = df2.groupby(lambda x: (x[0], dict_col[x[1]]), axis=1).sum()
out.columns = pd.MultiIndex.from_tuples(out.columns)

Another way is flatten the column levels by stack then unstack back after groupby:

df2.stack(level=0).groupby(dict_col, axis=1).sum().unstack(level=-1)

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top