Group by every combination of some columns on a Pandas Datafram

Use a powerset of columns to create different groupbys and then concat them:

from itertools import chain, combinations

def powerset(iterable):
    s = list(iterable)
    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))

dfe =pd.DataFrame()
for perm in powerset(df.columns[:-1]):
    features =list(perm)
    if len(features) != 0 and 'digimon' in features:
        dfe = pd.concat([dfe,df.groupby(features,as_index=False).agg({'points':'sum'})],axis=0)
        
dfe.fillna('all').sort_values(['type','stage','digimon'],ascending=False)

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top