How to implode(reverse of pandas explode) based on a column

前端 未结 2 729
[愿得一人]
[愿得一人] 2021-01-19 09:14

I have a dataframe df like below

  NETWORK       config_id       APPLICABLE_DAYS  Case    Delivery  
0   Grocery     5399            SUN               10              


        
2条回答
  •  梦谈多话
    2021-01-19 09:43

    Your results look more like a sum, than average; The solution below uses named aggregation :

        df.groupby(["NETWORK", "config_id"]).agg(
        APPLICABLE_DAYS=("APPLICABLE_DAYS", ",".join),
        Total_Cases=("Case", "sum"),
        Total_Delivery=("Delivery", "sum"),
    )
    
                            APPLICABLE_DAYS       Total_Cases   Total_Delivery
    NETWORK config_id           
    Grocery 5399                SUN,MON,TUE,WED           100      10
    

    If it is the mean, then you can change the 'sum' to 'mean' :

    df.groupby(["NETWORK", "config_id"]).agg(
        APPLICABLE_DAYS=("APPLICABLE_DAYS", ",".join),
        Avg_Cases=("Case", "mean"),
        Avg_Delivery=("Delivery", "mean"),
    )
    
                        APPLICABLE_DAYS   Avg_Cases Avg_Delivery
    NETWORK config_id           
    Grocery 5399         SUN,MON,TUE,WED      25      2.5
    

提交回复
热议问题