Sub topic 7
Shaping the result: index, as_index, and reset_index
This chapter assumes you can run the earlier groupby examples, know what a Series and an index are, and can select columns from a DataFrame. Here you will learn where the group keys end up in the result, and how to put them where you want them.
Where the keys go by default
When you aggregate a GroupBy object, pandas moves the group keys out of the columns and into the index of the result. The values you aggregated become the data.
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],
})
totals = df.groupby("region")["revenue"].sum()
print(totals)
# region
# North 175.0
# South 220.0
# Name: revenue, dtype: float64
print(totals.index.name)
# region
print(type(totals).__name__)
# SeriesTwo facts matter here. The index is named after the key (region). The result is a Series named after the aggregated column (revenue), because you selected one column with single brackets.
This default suits lookups such as totals["South"]. It is less convenient when you want to merge the result with another table, plot it, or write it to a file. Those tasks usually need the keys as ordinary columns.
Multiple keys produce a MultiIndex
With several keys, the index becomes a MultiIndex, a hierarchical index with one level per key. The level order matches the order of the keys you passed.
by_rp = df.groupby(["region", "product"])["revenue"].sum()
print(by_rp)
# region product
# North A 100.0
# B 75.0
# South A 100.0
# B 120.0
# Name: revenue, dtype: float64
print(by_rp.index.names)
# ['region', 'product']You can select from a MultiIndex by partial or full keys:
print(by_rp.loc["South"])
# product
# A 100.0
# B 120.0
# Name: revenue, dtype: float64
print(by_rp.loc[("South", "B")])
# 120.0A MultiIndex also lets you pivot one level into columns with unstack. This turns the long result into a small cross-table:
print(by_rp.unstack("product"))
# product A B
# region
# North 100.0 75.0
# South 100.0 120.0unstack is useful for display, and it introduces NaN for any region and product pair that does not exist in the data. Use it deliberately, not as a way to get the keys back into columns.
Getting the keys back as columns
There are two ways to turn the index levels into columns. They give the same table in most cases, so the choice is about readability and where in the chain you want to do it.
as_index=Falseis an argument togroupby. The keys are never moved into the index.reset_index()is a method on the result. It moves the index levels into columns and replaces the index with0, 1, 2, ....
a = df.groupby(["region", "product"], as_index=False)["revenue"].sum()
b = df.groupby(["region", "product"])["revenue"].sum().reset_index()
print(a)
# region product revenue
# 0 North A 100.0
# 1 North B 75.0
# 2 South A 100.0
# 3 South B 120.0
print(a.equals(b))
# TrueNote that as_index=False changes the return type. Selecting a column and aggregating now returns a DataFrame, not a Series.
print(type(df.groupby("region", as_index=False)["revenue"].sum()).__name__)
# DataFrame
print(type(df.groupby("region")["revenue"].sum()).__name__)
# SeriesChoosing between the two
Both routes work for sums and means. The differences show up at the edges.
| Situation | `as_index=False` | `reset_index()` |
|---|---|---|
| Result is a Series and you want a column name | Name comes from the selected column | Pass `name="..."` to choose |
| You already have a result with a MultiIndex | Not applicable, since the result exists already | Works on any result, even one you did not build |
| You want to keep the index for a later `unstack` or `.loc` | Not possible | Call it at the end of the chain |
| Aggregation names columns, such as named aggregation | Works | Works |
The rule of thumb is to use as_index=False when you know up front you want a flat table. Use reset_index() at the end of a longer chain, or when you need the indexed form for intermediate steps.
Naming the value column
A Series from a groupby is named after the column you aggregated. After reset_index(), that name becomes the name of the value column. You can override it with the name argument:
print(totals.reset_index(name="total_revenue"))
# region total_revenue
# 0 North 175.0
# 1 South 220.0With named aggregation, the output column names are already set by you, so reset_index() needs no arguments. It is the common way to finish a summary table.
summary = df.groupby("region").agg(
total_units=("units", "sum"),
avg_revenue=("revenue", "mean"),
n_products=("product", "nunique"),
)
print(summary.reset_index())
# region total_units avg_revenue n_products
# 0 North 15 87.500000 2
# 1 South 18 73.333333 2The as_index=False form gives the same table:
flat = df.groupby("region", as_index=False).agg(
total_units=("units", "sum"),
avg_revenue=("revenue", "mean"),
n_products=("product", "nunique"),
)
print(flat.equals(summary.reset_index()))
# TrueSingle brackets, double brackets
The shape of the result also depends on how you select the column. ["revenue"] gives a SeriesGroupBy, and [["revenue"]] gives a DataFrameGroupBy with one column. The second form always returns a DataFrame, even with the default as_index=True.
print(df.groupby("region")[["revenue"]].sum())
# revenue
# region
# North 175.0
# South 220.0This is a third way to get a DataFrame, but the keys are still in the index. Combine it with reset_index() or as_index=False if you need them as columns.
Counting with as_index=False
size() returns a Series, so its value column has no name of its own. With as_index=False, pandas names it size:
print(df.groupby("region", as_index=False).size())
# region size
# 0 North 2
# 1 South 3With the default settings, the equivalent is df.groupby("region").size().reset_index(name="n_rows"). Using name= here is usually clearer, since size is not a very descriptive column name.
Flattening multi-level columns
Passing a list of functions, or a dictionary of lists, to agg creates MultiIndex columns. That is a second kind of hierarchy to flatten:
multi = df.groupby("region").agg({"revenue": ["sum", "mean"]})
print(multi.columns.tolist())
# [('revenue', 'sum'), ('revenue', 'mean')]
multi.columns = ["_".join(c) for c in multi.columns]
print(multi.reset_index())
# region revenue_sum revenue_mean
# 0 North 175.0 87.500000
# 1 South 220.0 73.333333Named aggregation avoids this step, because each output column is named when you write it. If you control the code, prefer it.
Common errors
- Name collision in
reset_index(). If a column with the same name as an index level already exists, pandas raisesValueError: cannot insert region, already exists. This happens, for example, withdf.groupby("product")["product"].count().reset_index(), where the value column is also calledproduct. Passname="n"to rename the value column. - Expecting a Series. Code written for
as_index=Trueoften doesresult["South"]. After switching toas_index=False, that looks for a column namedSouthand raisesKeyError. Filter withresult[result["region"] == "South"]instead. - Losing the key order of the index.
reset_index()puts the former index levels first, in level order, followed by the value columns. If you need another column order, select explicitly withresult[["product", "region", "revenue"]]. - Forgetting the index is not 0..n-1. After a plain
groupbythe index holds group keys. Positional code such asresult.iloc[0]still works, butresult.loc[0]does not.
Exercises
Exercise
You run df.groupby(["region", "product"])["units"].sum() and want a DataFrame with columns region, product, and total_units, in that order. Write two different ways to get it.
Show answer
Option 1: df.groupby(["region", "product"], as_index=False)["units"].sum().rename(columns={"units": "total_units"}). Option 2: df.groupby(["region", "product"])["units"].sum().reset_index(name="total_units"). Both return the three columns in the order region, product, total_units with a default 0..n-1 index.
Exercise
Why does df.groupby("product")["product"].count().reset_index() raise an error, and how do you fix it?
Show answer
The count is a Series named product with an index also named product. reset_index() tries to insert the index as a column called product, but a column with that name would already exist in the result, so it raises ValueError. Fix it by naming the value column: .reset_index(name="n").