[Python] How to group by multiple columns and apply a custom function in pandas?

Discussão em 'Python' iniciado por Stack, Maio 5, 2025.

  1. Stack

    Stack Membro Participativo

    I have a DataFrame in pandas with multiple columns like ['category', 'sub_category', 'value'], and I want to group by both category and sub_category, and then apply a custom function to the value column (e.g. weighted average or a conditional calculation).

    I’m not sure how to properly use groupby().apply() or agg() for this. Could someone show the cleanest way to do this with an example?

    I tried this:

    df.groupby(['category', 'sub_category'])['value'].apply(my_custom_function)


    But I got an error when my function expected more than just the Series.

    Continue reading...

Compartilhe esta Página