# Pandas - Avoid boolean result when using groupby()

I have this script:

    sectors = df.groupby(['company_sector']).mean()['investment_in_millions']


Output:

I wanted to keep the same groupy() but having a result in "investment_in_millions" column filtered as mean > 10 or another value.

If apply this:

     sectors = df.groupby(['company_sector']).mean()['investment_in_millions']>10


I keep the groupby() but it returns a boolean into the investment column.

If I use:

     filtered = df[df['investment_in_millions']>10]


I get the filtered values mean>10 but the groupby() is not there anymore and I get all the other columns in the excel.

How can I get the groupby() together with the mean>10 without getting a boolean result?

Thanks!

First filter your results:

filtered_df = df[df['investment_in_millions']>10]


And then group it by company_sector

import numpy as np

sectors = filtered_df.groupby(['company_sector']).agg({"investment_in_millions":np.mean})


You can do it in one line:

sectors = df[df['investment_in_millions']>10].groupby(['company_sector']).agg({"investment_in_millions":np.mean})

• thank you! Can I ask you why .agg needs a dictionary? – Steven Aug 5 '20 at 7:50
• Sure!, this is quite useful since you can specify inside the dictionary, more than one column and apply them virtually any aggregate function – Julio Jesus Aug 5 '20 at 13:57
• ok, I see. Thanks again! – Steven Aug 5 '20 at 14:00