Apply multiple functions to multiple groupby columns

前端 未结 7 2079
春和景丽
春和景丽 2020-11-22 03:16

The docs show how to apply multiple functions on a groupby object at a time using a dict with the output column names as the keys:

In [563]: grouped[\'D\'].a         


        
相关标签:
7条回答
  • 2020-11-22 04:21

    This is a twist on 'exans' answer that uses Named Aggregations. It's the same but with argument unpacking which allows you to still pass in a dictionary to the agg function.

    The named aggs are a nice feature, but at first glance might seem hard to write programmatically since they use keywords, but it's actually simple with argument/keyword unpacking.

    animals = pd.DataFrame({'kind': ['cat', 'dog', 'cat', 'dog'],
                             'height': [9.1, 6.0, 9.5, 34.0],
                             'weight': [7.9, 7.5, 9.9, 198.0]})
     
    agg_dict = {
        "min_height": pd.NamedAgg(column='height', aggfunc='min'),
        "max_height": pd.NamedAgg(column='height', aggfunc='max'),
        "average_weight": pd.NamedAgg(column='weight', aggfunc=np.mean)
    }
    
    animals.groupby("kind").agg(**agg_dict)
    

    The Result

          min_height  max_height  average_weight
    kind                                        
    cat          9.1         9.5            8.90
    dog          6.0        34.0          102.75
    
    0 讨论(0)
提交回复
热议问题