Using GroupBy with Lambda functions in Pandas
7. Using GroupBy with Lambda functions
Write a Pandas program to use lambda functions within groupby for flexible and efficient data transformations.
Sample Solution:
Python Code :
import pandas as pd
# Sample DataFrame
data = {'Category': ['A', 'A', 'B', 'B', 'C', 'C'],
'Value': [5, 15, 25, 35, 45, 55]}
df = pd.DataFrame(data)
print("Sample DataFrame:")
print(df)
# Group by 'Category' and apply lambda function
print("\nGroup by 'Category' and apply lambda function:")
grouped = df.groupby('Category').agg(lambda x: x.max() - x.min())
print(grouped)
Output:
Sample DataFrame: Category Value 0 A 5 1 A 15 2 B 25 3 B 35 4 C 45 5 C 55 Group by 'Category' and apply lambda function: Value Category A 10 B 10 C 10
Explanation:
- Import pandas.
- Create a sample DataFrame.
- Group by 'Category'.
- Apply a lambda function to calculate the range of values.
- Print the result.
For more Practice: Solve these Related Problems:
- Write a Pandas program to group data and apply a lambda function that computes the percentage share of each record within its group.
- Write a Pandas program to group a DataFrame and use a lambda function to filter each group based on the relative ranking of values.
- Write a Pandas program to group data and apply a lambda that returns the difference between each value and the group median.
- Write a Pandas program to group data and use a lambda function to standardize values within each group.
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Aggregate with different functions on different columns in Pandas.
Next: Grouping and Aggregating with multiple Index Levels in Pandas.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.