Using GroupBy with Lambda functions in Pandas
Pandas Advanced Grouping and Aggregation: Exercise-7 with Solution
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.
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.
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://198.211.115.131/python-exercises/pandas/advanced-grouping-and-aggregation/using-groupby-with-lambda-functions-in-pandas.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics