Home > Backend Development > Python Tutorial > How Can I Perform Multiple Aggregations on the Same Column Using Pandas GroupBy.agg()?

How Can I Perform Multiple Aggregations on the Same Column Using Pandas GroupBy.agg()?

Patricia Arquette
Release: 2024-12-06 17:50:15
Original
1025 people have browsed it

How Can I Perform Multiple Aggregations on the Same Column Using Pandas GroupBy.agg()?

Multiple Aggregations on the Same Column with Pandas GroupBy.agg()

In pandas, GroupBy.agg() allows for convenient aggregation of data by applying a function to each column. However, it becomes necessary to call agg() multiple times when applying different functions to the same column.

Traditional (Incorrect) Approach:

The intuitively straightforward approach would be:

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

Unfortunately, this results in an error due to duplicate keys.

Solution:

Since agg() expects a dictionary, the straightforward solution is to create a dictionary with the column name and a list of functions:

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

This will result in a multi-index DataFrame with the output of both aggregations.

Example:

Consider the following DataFrame:

import pandas as pd
import datetime as dt
import numpy as np

pd.np.random.seed(0)
df = pd.DataFrame({
    "date": [dt.date(2012, x, 1) for x in range(1, 11)],
    "returns": 0.05 * np.random.randn(10),
    "dummy": np.repeat(1, 10)
})
Copy after login

To apply both mean and sum to the "returns" column:

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

This will produce:

           returns          
           mean       sum
dummy                    
1      0.036901  0.369012
Copy after login

The above is the detailed content of How Can I Perform Multiple Aggregations on 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