Search code examples
pythonpandaspandas-groupbymulti-index

How to get the count and total sum of a MultiIndex Data frame


df_n_pr_stores_qty.groupby(['Store_type','prod_cat']).count()

                             QTY
Store_type      prod_cat    

Flagship        Bags        2726
                Books       14766
                Clothing    5844
                Electronics 9950
MBR             Bags        2936
                Books       14868
                Clothing    6198
                Footwear    6105
TeleShop        Bags        2854
                Books       13836
  • How to get the which store has count of prod_cat of each store in descending order
  • What is the Total Qty of each order

Expected Out q1

Flagship        4
MBR             4
TeleShop        2

q2

Flagship    33,296‬
MBR         ‭30,107‬
TeleShop    ‭16,690‬    

Solution

  • Here's a way to do:

    # df is your multiindex df
    >>> df.groupby(level=0).count()
    
                values
    Store_type        
    Flagship         4
    MBR              4
    TeleShop         2
    
    >>> df.groupby(level=0).sum()
    
                values
    Store_type        
    Flagship     33286
    MBR          30107
    TeleShop     16690