Sub topic 7
Shaping the result: index, as_index, and reset_index
This chapter assumes you can build a DataFrame, select columns, and know what a pandas index is. It also assumes you have run a basic groupby(...).sum(). Here you will learn why the result of an aggregation has the index it has, and how to turn it into the layout you need.
Where the group keys go
After an aggregation, pandas moves the grouping keys into the index of the result. The values you aggregated stay as data. Use this setup for every example:
import pandas as pd
df = pd.DataFrame({
"region": ["North", "North", "South", "South", "South"],
"product": ["A", "B", "A", "A", "B"],
"units": [10, 5, 7, 3, 8],
"revenue": [100.0, 75.0, 70.0, 30.0, 120.0],
})
by_two = df.groupby(["region", "product"])["revenue"].sum()
print(by_two)
# region product
# North A 100.0
# B 75.0
# South A 100.0
# B 120.0
# Name: revenue, dtype: float64With one key, the index is a plain index named after the key. With several keys, it is a MultiIndex, which has one level per key. The result is a Series because you selected a single column with ["revenue"].
Getting the keys back as columns
You have two ways to keep keys as ordinary columns. Both give the same table.
flat = df.groupby(["region", "product"], as_index=False)["revenue"].sum()
print(flat)
# region product revenue
# 0 North A 100.0
# 1 North B 75.0
# 2 South A 100.0
# 3 South B 120.0
same = by_two.reset_index()
print(same.equals(flat))
# Trueas_index=False decides this when the groupby is created. reset_index() fixes it afterwards. Use reset_index() when you want to inspect the indexed result first. Use as_index=False in a one-line pipeline.
Both return a DataFrame with a fresh 0-based row index. That makes it easy to merge the result with another table on the key columns.
When to keep the index
The index is useful when you want to look up values by key or align two results. Selecting by key is direct, and arithmetic between two results aligns on the index labels.
totals = df.groupby("region")["revenue"].sum()
print(totals.loc["South"])
# 220.0For a MultiIndex, you can pivot one level into columns with unstack():
table = by_two.unstack()
print(table)
# product A B
# region
# North 100.0 75.0
# South 100.0 120.0Common errors
- Series versus DataFrame.
df.groupby("region")["revenue"].sum()returns a Series.df.groupby("region")[["revenue"]].sum()returns a DataFrame. This matters when you callreset_index()or chain DataFrame methods. - Name collisions.
reset_index()on a Series inserts a column named after the index level. If the Series name is the same as the level name, pandas raisesValueError: cannot insert ..., already exists. Rename the Series first, or usename="new_name"inreset_index. - Expecting
as_index=Falseto change the values. It only changes where the keys live. The grouping and the numbers are the same. - Row labels after
as_index=False. The index is a default range, so labels such as0and1carry no meaning. Do not treat them as group identifiers.
Exercise
You run df.groupby(["region", "product"])["units"].sum(). Name two ways to get a DataFrame with region and product as ordinary columns, and say what type the original result is.
Show answer
The original result is a Series with a two-level MultiIndex. Call .reset_index() on it, or pass as_index=False to groupby. Both return a DataFrame with region, product, and units columns and a 0-based row index.