How to apply multiple aggregation to a groupby object at once?

Hey so, for example,
a table has columns similar to this
setup_job start_time end_time setup_job_time channel input output
0 COMPLETED 1557417255 1557418814 25.0 SMS 12833.0 12810.0
1 COMPLETED 1557417222 1557418829 26.0 IVR 12724.0 12588.0

So I want to group by channel and the resulting data frame should have the sum of output by the channel and min of the start_time columns and max of the end_time column.

I know how to do them individually but i want to know if we can have all in one resulting table.

How can we achieve it?

Hi @ankit256,

If I understand your query correctly you want to use multiple aggregations at once so that they all appear in one result.

In that case, I believe this is what you are looking for pandas.core.groupby.DataFrameGroupBy.agg. You can use the .agg() method to apply multiple aggregations to the pandas.core.groupby.groupby.DataFrameGroupBy object. And to do so you have to provide a dictionary as input where the keys are column names and values are the aggregate function you wish to apply to that column.

Here is a short reproducible example:

import pandas as pd

df = pd.DataFrame({
        'Type': ['Fruit', 'Vegetable','Fruit', 'Vegetable', 'Vegetable'],
        'Name': ['Apple', 'Broccoli', 'Orange', 'Carrot', 'Onion'],
        'Count': [10, 5, 10, 20, 30],
        'Total_Weight_(kg)': [0.85, 1.28, 1.3, 1.4, 4.5]

        Type      Name  Count  Total_Weight_(kg)
0      Fruit     Apple     10               0.85
1  Vegetable  Broccoli      5               1.28
2      Fruit    Orange     10               1.30
3  Vegetable    Carrot     20               1.40
4  Vegetable     Onion     30               4.50
        'Count': 'sum',
        'Total_Weight_(kg)': 'mean'
           Count  Total_Weight_(kg)
Fruit         20           1.075000
Vegetable     55           2.393333

Hope this helps. :slightly_smiling_face:

Let me know if you were looking for something else.


Hey @Sahil This works great. Thanks a lot.