w3resource

Using named Aggregations in Pandas GroupBy


Pandas Advanced Grouping and Aggregation: Exercise-10 with Solution


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.

Python Code Editor:

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

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

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.