【问题标题】:How to get the count and total sum of a MultiIndex Data frame如何获取 MultiIndex 数据帧的计数和总和
【发布时间】:2020-04-22 23:07:48
【问题描述】:

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
  • 如何按降序获取每个商店的prod_cat计数的哪个商店
  • 每个订单的总数量是多少

预计出q1

Flagship        4
MBR             4
TeleShop        2

q2

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

【问题讨论】:

    标签: python pandas pandas-groupby multi-index


    【解决方案1】:

    这是一种方法:

    # 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
    

    【讨论】:

      【解决方案2】:
      df = pd.read_clipboard(index_col=0, sep='\s\s+')
      

      1:

      df.groupby(level=0).count()
      

      2:

      df.groupby(level=0).sum()
      

      或者,如果您有很多列:

      df.groupby(level=0).agg({"QTY": "sum"})
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-01
        • 2018-10-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多