w3resource

GroupBy and Apply different functions using a Dictionary in Pandas

Pandas Advanced Grouping and Aggregation: Exercise-12 with Solution

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.

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/pandas/advanced-grouping-and-aggregation/groupby-and-apply-different-functions-using-a-dictionary-in-pandas.php