Group by and Apply function to Groups in Pandas
Pandas Advanced Grouping and Aggregation: Exercise-5 with Solution
Group by and Apply function:
Write a Pandas program to group data and apply custom functions to groups for flexible data transformations.
Sample Solution:
Python Code :
import pandas as pd
# Sample DataFrame
data = {'Category': ['A', 'A', 'B', 'B', 'C', 'C'],
'Value': [10, 20, 30, 40, 50, 60]}
df = pd.DataFrame(data)
print("Sample DataFrame:")
print(df)
# Define function to apply to each group
def scale_values(x):
return x / x.max()
# Group by 'Category' and apply function
print("\nGroup by 'Category' and apply function:")
grouped = df.groupby('Category').transform(scale_values)
print(grouped)
Output:
Sample DataFrame: Category Value 0 A 10 1 A 20 2 B 30 3 B 40 4 C 50 5 C 60 Group by 'Category' and apply function: Value 0 0.500000 1 1.000000 2 0.750000 3 1.000000 4 0.833333 5 1.000000
Explanation:
- Import pandas.
- Create a sample DataFrame.
- Define a function to scale values within each group.
- Group by 'Category' and apply the function.
- Print the transformed DataFrame.
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Use Custom Aggregation Functions in Pandas GroupBy.
Next: Aggregate with different functions on different columns in Pandas.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics