Last updated
Aggregating Data
Definition: Aggregation reduces many rows to summary numbers. With agg you can calculate several statistics at once, for the whole table or per group.
Example 1 — several stats per group
import pandas as pd
df = pd.DataFrame({
"cat": ["x", "y", "x", "y"],
"val": [1, 2, 3, 4]
})
print(df.groupby("cat")["val"].agg(["sum", "mean", "count"]))
Example 2 — quick whole-table stats
import pandas as pd
df = pd.DataFrame({"price": [10, 20, 30, 40]})
print("Sum: ", df["price"].sum())
print("Mean:", df["price"].mean())
print("Max: ", df["price"].max())
Example 3 — different stats per column
import pandas as pd
df = pd.DataFrame({"price": [10, 20, 30], "qty": [2, 3, 4]})
print(df.agg({"price": "mean", "qty": "sum"}))
💡 Tip: combining groupby with agg answers most business questions — "average sales per region", "total orders per month", and so on.
Try it Yourself
Output
Ad · responsive