Group by and Apply function to Groups in Pandas
5. 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.
For more Practice: Solve these Related Problems:
- Write a Pandas program to group data and apply a function that normalizes the values within each group.
- Write a Pandas program to group a DataFrame and apply a custom function that returns the top two records from each group.
- Write a Pandas program to group data and apply a function that transforms each group's data by subtracting the group mean.
- Write a Pandas program to group data and apply a complex transformation function that computes a rolling window statistic within groups.
Go to:
PREV : Group by and Filter Groups.
NEXT : Aggregating with different functions on different Columns.
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.
