w3resource

Using named Aggregations in Pandas GroupBy


10. Using named Aggregations

Write a Pandas program to use named aggregations in GroupBy to make your data aggregation operations more readable and organized.

Sample Solution:

Python Code :

import pandas as pd

# Sample DataFrame
data = {'Category': ['A', 'A', 'B', 'B', 'C', 'C'],
        'Value1': [5, 10, 15, 20, 25, 30],
        'Value2': [50, 100, 150, 200, 250, 300]}

df = pd.DataFrame(data)
print("Sample DataFrame:")
print(df)

# Group by 'Category' and apply named aggregations
print("\nGroup by 'Category' and apply named aggregations:")
grouped = df.groupby('Category').agg(
    Value1_mean=('Value1', 'mean'),
    Value2_sum=('Value2', 'sum')
)

print(grouped)

Output:

Sample DataFrame:
  Category  Value1  Value2
0        A       5      50
1        A      10     100
2        B      15     150
3        B      20     200
4        C      25     250
5        C      30     300

Group by 'Category' and apply named aggregations:
          Value1_mean  Value2_sum
Category                         
A                 7.5         150
B                17.5         350
C                27.5         550

Explanation:

  • Import pandas.
  • Create a sample DataFrame.
  • Group by 'Category'.
  • Apply named aggregations: mean for 'Value1' and sum for 'Value2'.
  • Print the result.

For more Practice: Solve these Related Problems:

  • Write a Pandas program to group data and use named aggregations to clearly label the output of each aggregation function.
  • Write a Pandas program to perform groupby operations with named aggregations that compute multiple statistics for each group.
  • Write a Pandas program to group data and apply named aggregations, then format the resulting DataFrame for improved readability.
  • Write a Pandas program to combine named aggregations with filtering, so that only groups meeting a criterion are aggregated.

Go to:


Previous: Grouping and Aggregating with multiple Index Levels in Pandas.
Next: Combining GroupBy with Transform in Pandas.

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.