groupby() itself doesn't compute anything immediately — it returns a lazy GroupBy object representing the split-apply-combine plan, which only actually does work once you chain an aggregation, like .sum(), .mean(), or .agg(), or another operation onto it. Grouping by multiple columns, passing a list, creates one group per unique combination of those columns' values, and by default the grouped columns become the resulting index unless you pass as_index=False to keep them as regular columns instead.
1Understanding df.groupby()
groupby() itself doesn't compute anything immediately — it returns a lazy GroupBy object representing the split-apply-combine plan, which only actually does work once you chain an aggregation, like .sum(), .mean(), or .agg(), or another operation onto it. Grouping by multiple columns, passing a list, creates one group per unique combination of those columns' values, and by default the grouped columns become the resulting index unless you pass as_index=False to keep them as regular columns instead.
groupby() alone doesn't print anything useful and doesn't compute results — it returns a lazy GroupBy object that only actually does work once you chain an aggregation method, like .sum() or .mean(), onto it.
import pandas as pd
df = pd.DataFrame({"team": ["A", "B", "A", "B"], "score": [10, 20, 15, 25]})
print(df.groupby("team")["score"].sum())2Practical Example
Here is a real-world application of df.groupby() showing how it is used in production Pandas code.
import pandas as pd
df = pd.DataFrame({"team": ["A", "B", "A", "B"], "score": [10, 20, 15, 25]})
print(df.groupby("team", as_index=False)["score"].mean())3Best Practices
Follow these guidelines when working with df.groupby():
1. Chain a specific aggregation (.sum(), .mean(), .agg(), etc.) onto groupby() rather than trying to inspect or print the raw GroupBy object directly
2. Pass as_index=False when you want the grouping column(s) to remain regular columns in the result, rather than becoming the new index
3. Group by a list of multiple columns when you need one group per unique combination of several categorical fields, not just one
Tip: groupby() alone doesn't print anything useful and doesn't compute results — it returns a lazy GroupBy object that only actually does work once you chain an aggregation method, like .sum() or .mean(), onto it.
import pandas as pd
df = pd.DataFrame({"team": ["A", "B", "A", "B"], "score": [10, 20, 15, 25]})
print(df.groupby("team")["score"].sum())