[Python] Picking N largest from a group in Pandas

Discussão em 'Python' iniciado por Stack, Julho 1, 2025.

  1. Stack

    Stack Membro Participativo

    I want to get the top 5 from an aggregate mean measure.

    cohort = ['year','month','maincategory','subcategory']
    poorresult = stmpoor.groupby(cohort,as_index=False).agg({'resolvetime': ['count','mean'], 'grouptransfers': ['mean']}).apply(lambda x: x.nlargest(5, ('resolvetime','mean'))


    but that threw an error mentioning the keep keyword. Error said

    ValueError: keep must be either "first", "last" or "all"


    I looked up the keep keyword and then I tried

    poorresult = stmpoor.groupby(cohort,as_index=False).agg({'resolvetime': ['count','mean'], 'grouptransfers': ['mean']})# .apply(lambda x: x.nlargest(5, ('resolvetime','mean'),keep='all'))


    but that did not work either. The error was

    TypeError: Series.nlargest() got multiple values for argument 'keep'


    What is the correct syntax?

    Continue reading...

Compartilhe esta Página