I have this script:

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


enter image description here

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?



1 Answer 1


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})
  • $\begingroup$ thank you! Can I ask you why .agg needs a dictionary? $\endgroup$
    – Steven
    Aug 5, 2020 at 7:50
  • 1
    $\begingroup$ Sure!, this is quite useful since you can specify inside the dictionary, more than one column and apply them virtually any aggregate function $\endgroup$
    – Multivac
    Aug 5, 2020 at 13:57
  • $\begingroup$ ok, I see. Thanks again! $\endgroup$
    – Steven
    Aug 5, 2020 at 14:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.