Grouping rows together
.groupby() splits a DataFrame into groups sharing the same value in one column -- it computes nothing by itself, it just sets up the split:
grouped = df.groupby("dept")
Aggregating each group
Follow it with a column and a summary function to actually compute something, one result per group:
totals = df.groupby("dept")["sales"].sum()
print(totals)
dept
Eng 250
Sales 150
Name: sales, dtype: int64
The result is a Series indexed by the group names (Eng, Sales, ...) -- other common aggregations are .mean(), .count(), and .max().
Pulling out one group's result
Use .loc[] with the group's label to get a single value back out of that Series:
print(totals.loc["Eng"]) # 250
Sorting
print(df.sort_values("score", ascending=False)) # highest first
Why This Matters for Your Exams
"Group by X, then total/average Y" is the shape of most real data-analysis questions -- sales by region, average score by class, count by category. .groupby(X)[Y].sum() (or .mean(), .count()) is the whole pattern; everything else is just which column goes where.
Try it yourself
Real-time practice is a paid add-on
Reading units and the practice quiz are free. Pay once to unlock running real code for DATASCI.

