w3resource

GroupBy and Apply different functions using a Dictionary in Pandas


12. GroupBy and Applying Different Functions Using a Dictionary

Write a Pandas program that uses dictionaries to apply different functions to different columns in GroupBy.

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 functions using a dictionary
print("\nGroup by 'Category' and apply different functions using a dictionary:")
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 functions using a dictionary:
          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' using a dictionary.
  • Print the result.

For more Practice: Solve these Related Problems:

  • Write a Pandas program to group data and apply a dictionary of functions to different columns, then display the aggregated results.
  • Write a Pandas program to use a dictionary in groupby to apply sum to one column and mean to another, then merge the outputs.
  • Write a Pandas program to group a DataFrame and pass a dictionary of custom functions to different columns for tailored analysis.
  • Write a Pandas program to use groupby with a dictionary mapping column names to aggregation functions and then rename the resulting columns.

Python Code Editor:

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

Previous: Combining GroupBy with Transform in Pandas.
Next: GroupBy and create a new column with Aggregated data 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.