[Python] Can I define a Pandas DataFrame GroupBy aggregation involving multiple columns?

Discussão em 'Python' iniciado por Stack, Fevereiro 12, 2025.

  1. Stack

    Stack Membro Participativo

    I have experimented and read the documentation for DataFrameGroupBy.aggregate, but it is not clear to me whether - and how I can define an aggregation that works on multiple columns. It seems to me like aggregations specified with keyword argument assignment to new columns only work on single columns as input.

    If I have a simple data frame like:

    df = pd.DataFrame({"value1": range(8), "value2": range(7, -1, -1), "Sample": [1, 2]*4, "Year": list(range(2023, 2027))*2})


    I would like to be able to do something like:

    df.groupby(["Sample", "Year"]).agg(agg1 = lambda group: (group["value1"] * group["value2"]).mean())


    where I was hoping my callable would be given each entire group as a sub-DataFrame, but this does not work.

    Is it possible to do this kind of aggregation and how?

    Continue reading...

Compartilhe esta Página