Home > Backend Development > Python Tutorial > How Can I Apply Multiple Aggregation Functions to the Same Column Using Pandas GroupBy.agg()?

How Can I Apply Multiple Aggregation Functions to the Same Column Using Pandas GroupBy.agg()?

Patricia Arquette
Release: 2025-01-01 00:22:09
Original
260 people have browsed it

How Can I Apply Multiple Aggregation Functions to the Same Column Using Pandas GroupBy.agg()?

Multiple Aggregations of the Same Column Using pandas GroupBy.agg()

Problem:

How can you apply multiple aggregating functions (f1, f2) to the same column ("returns") in a pandas DataFrame using GroupBy.agg() without calling agg() multiple times?

Intuition:

It would be convenient to have a syntax like:

df.groupby("dummy").agg({"returns": [f1, f2]})
Copy after login

Solution:

As of 2022-06-20, the following syntax is the accepted practice:

df.groupby('dummy').agg(
    Mean=('returns', np.mean),
    Sum=('returns', np.sum),
)
Copy after login

This syntax uses tuples to specify the (column, function) pairs for aggregation.

Historical Solutions:

In earlier versions of pandas, you could use one of the following solutions:

  • List of Functions:

    df.groupby("dummy").agg({"returns": [np.mean, np.sum]})
    Copy after login
  • Dictionary with Function List:

    df.groupby('dummy').agg({'returns':
                                 {'Mean': np.mean, 'Sum': np.sum}})
    Copy after login

These earlier solutions are still valid, but the first option using tuples is now considered best practice.

The above is the detailed content of How Can I Apply Multiple Aggregation Functions to the Same Column Using Pandas GroupBy.agg()?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template