w3resource

Aggregate with different functions on different columns in Pandas


6. Aggregating with different functions on different Columns

Write a Pandas program to use different aggregation functions on different columns for versatile data analysis.

Sample Solution:

Python Code :

import pandas as pd
# Sample DataFrame
data = {'Category': ['A', 'A', 'B', 'B', 'C', 'C'],
        'Value1': [1, 2, 3, 4, 5, 6],
        'Value2': [10, 20, 30, 40, 50, 60]}
df = pd.DataFrame(data)
print("Sample DataFrame:")
print(df)
# Group by 'Category' and apply different aggregations
print("\nGroup by 'Category' and apply different aggregations:")
grouped = df.groupby('Category').agg({'Value1': 'sum', 'Value2': 'mean'})
print(grouped)

Output:

Sample DataFrame:
  Category  Value1  Value2
0        A       1      10
1        A       2      20
2        B       3      30
3        B       4      40
4        C       5      50
5        C       6      60

Group by 'Category' and apply different aggregations:
          Value1  Value2
Category                
A              3    15.0
B              7    35.0
C             11    55.0

Explanation:

  • Import pandas.
  • Create a sample DataFrame.
  • Group by 'Category'.
  • Apply sum aggregation on 'Value1' and mean aggregation on 'Value2'.
  • Print the result.

For more Practice: Solve these Related Problems:

  • Write a Pandas program to group data and apply a sum aggregation on one column and a mean aggregation on another column.
  • Write a Pandas program to group a DataFrame and use different functions on different columns as defined in a dictionary mapping.
  • Write a Pandas program to perform groupby operations and aggregate one column with max while aggregating another with a custom function.
  • Write a Pandas program to group data and then aggregate multiple columns with distinct functions, finally renaming the resulting columns.

Python Code Editor:

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

Previous: Group by and Apply function to Groups in Pandas.
Next: Using GroupBy with Lambda functions 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.