How to Group Variables in Python to Calculate Count, Average, and Sum
Share
Condition for Grouping Variables in Python to Calculate Count, Average, and Sum
Description:
In Python, grouping variables to calculate counts, averages, or sums can be done using the pandas library.
Specifically, the groupby() function is used to group data based on certain variables, and then you can perform various aggregation operations like count(), mean(), and sum() on each group.
# Group by 'Store' and calculate count, average (mean), and sum for 'Sales' and 'Quantity'
grouped = df.groupby('Store').agg(
Sales_Count=('Sales', 'count'),
Sales_Avg=('Sales', 'mean'),
Sales_Sum=('Sales', 'sum'),
Quantity_Sum=('Quantity', 'sum')
)