w3resource

Apply different functions to different columns with GroupBy


9. Applying different functions to different columns with GroupBy

Write a Pandas program that applies different functions to different columns in Pandas GroupBy for tailored data analysis.

Sample Solution:

Python Code :

import pandas as pd

# Sample DataFrame
data = {'Category': ['A', 'A', 'B', 'B', 'C', 'C'],
        'Value1': [10, 20, 30, 40, 50, 60],
        'Value2': [100, 200, 300, 400, 500, 600]}

df = pd.DataFrame(data)
print("Sample DataFrame:")
print(df)
# Group by 'Category' and apply different functions
print("\nGroup by 'Category' and apply different functions:")
grouped = df.groupby('Category').agg({'Value1': 'mean', 'Value2': 'sum'})
print(grouped)

Output:

Sample DataFrame:
  Category  Value1  Value2
0        A      10     100
1        A      20     200
2        B      30     300
3        B      40     400
4        C      50     500
5        C      60     600

Group by 'Category' and apply different functions:
          Value1  Value2
Category                
A           15.0     300
B           35.0     700
C           55.0    1100

Explanation:

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

For more Practice: Solve these Related Problems:

  • Write a Pandas program to group data and apply a sum on one column while applying a custom aggregation on another, using a dictionary.
  • Write a Pandas program to group data and apply distinct functions to separate columns, then merge the results into a single DataFrame.
  • Write a Pandas program to group a DataFrame and use different aggregation functions on various columns, ensuring each output column is renamed.
  • Write a Pandas program to group data and apply lambda functions to different columns, displaying results side-by-side.

Go to:


Previous: Grouping and Aggregating with multiple Index Levels in Pandas.
Next: Calculating Percentage change in Resampled data.

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.