Sub topic 10
Flattening columns and calling reset_index
This chapter assumes you can build a pivot_table and know what a MultiIndex is. The previous chapter covered how to read MultiIndex columns. Here you learn how to turn a pivot result back into an ordinary table. That means one string name per column and the row labels back as a regular column.
Why flatten at all
A pivot result is a table whose labels carry information. The row labels sit in the index, and the column labels may sit in two or more levels. That works well inside pandas. It works badly almost everywhere else:
- Writing to CSV, a database, or Parquet needs plain column names.
- Merging on a key needs that key as a column, or at least an index with a matching name.
- Plotting libraries, dashboards, and other people's code usually expect a flat table.
- Selecting with
df["sum_jan"]is shorter thandf[("sum", "jan")].
Two separate jobs are involved, and they are easy to mix up:
- Restoring the index.
reset_indexmoves the row labels into ordinary columns. - Flattening the columns. Joining the levels of a
MultiIndexinto single strings.
The code blocks below share one script. Run them in order.
Setup
import pandas as pd
sales = pd.DataFrame({
"store": ["A", "A", "B", "B"],
"month": ["jan", "jan", "jan", "feb"],
"sales": [60, 40, 80, 90],
"units": [6, 4, 8, 9],
})Store A has two January rows, so you need pivot_table and not pivot.
Restoring the index with reset_index
Start with a pivot that has a single column level.
table = sales.pivot_table(
index="store", columns="month", values="sales", aggfunc="sum"
)
print(table.index.name)
print(list(table.columns.names))
print(table.columns.tolist())
flat = table.reset_index()
print(flat.columns.tolist())
print(flat.columns.name)The output is:
store
['month']
['feb', 'jan']
['store', 'feb', 'jan']
monthreset_index moved store out of the index and into the first column. The index is now a default RangeIndex (0, 1, ...).
The last line shows a leftover. The column axis still has the name month. When you print the frame, month appears in the corner above the row numbers, and it looks like a column header even though it is not a column. Remove it:
flat.columns.name = NoneYou can also do this inside a method chain:
flat = (
sales.pivot_table(index="store", columns="month", values="sales", aggfunc="sum")
.rename_axis(columns=None)
.reset_index()
)
print(flat.columns.tolist())This prints ['store', 'feb', 'jan']. Use rename_axis(columns=None) when you want to keep the whole transformation as a single expression.
What reset_index does in other situations
| Situation | Result |
|---|---|
| Index has a name (`store`) | The name becomes the new column's name |
| Index has no name | The new column is called `index` (or `level_0` if `index` is taken) |
| Index has several levels | Each level becomes its own column |
| `drop=True` | The index is discarded and no column is created |
| A column with that name already exists | `ValueError: cannot insert store, already exists` |
If the unnamed index gives you a column called index, name it directly with reset_index(names="store_id"). The names argument needs pandas 1.5 or later. On older versions, call rename_axis("store_id") before reset_index().
Flattening MultiIndex columns
Passing a list of aggregation functions, or a list of values, creates a second column level.
multi = sales.pivot_table(
index="store",
columns="month",
values="sales",
aggfunc=["sum", "count"],
)
print(multi.columns.tolist())[('sum', 'feb'), ('sum', 'jan'), ('count', 'feb'), ('count', 'jan')]Each column label is a tuple. Flattening means joining each tuple into one string.
multi.columns = ["_".join(map(str, col)) for col in multi.columns]
multi = multi.reset_index()
print(multi.columns.tolist())['store', 'sum_feb', 'sum_jan', 'count_feb', 'count_jan']map(str, col) converts every part to a string first. This matters when a level holds numbers such as years, because "_".join fails on integers.
Store A has no February row. Its sum_feb and count_feb cells are therefore NaN, and the columns they belong to become floats. Add fill_value=0 to pivot_table, or call fillna afterward, if you need integers.
The order of the two steps matters
wrong = sales.pivot_table(
index="store", columns="month", values="sales", aggfunc=["sum", "count"]
).reset_index()
print(["_".join(map(str, col)) for col in wrong.columns])['store_', 'sum_feb', 'sum_jan', 'count_feb', 'count_jan']A reusable helper
This function handles single-level and multi-level columns, and it skips empty parts, so it works in either order.
def flatten_columns(df, sep="_"):
df = df.copy()
df.columns = [
sep.join(str(part) for part in col if str(part) != "")
if isinstance(col, tuple)
else col
for col in df.columns
]
return df
result = flatten_columns(
sales.pivot_table(
index="store", columns="month", values="sales", aggfunc=["sum", "count"]
).reset_index()
)
print(result.columns.tolist())The output is ['store', 'sum_feb', 'sum_jan', 'count_feb', 'count_jan']. The isinstance(col, tuple) check matters. Without it, a plain string label would be iterated character by character, and "store" would become s_t_o_r_e.
Flattening when you pass several values
With a list in values, the first level holds the value column names and the second level holds the pivoted month labels.
two = sales.pivot_table(
index="store",
columns="month",
values=["sales", "units"],
aggfunc="sum",
fill_value=0,
)
print(two.columns.tolist())
two.columns = [f"{month}_{value}" for value, month in two.columns]
two = two.reset_index()
print(two.columns.tolist())[('sales', 'feb'), ('sales', 'jan'), ('units', 'feb'), ('units', 'jan')]
['store', 'feb_sales', 'feb_units', 'jan_sales', 'jan_units']Notice the unpacking in the list comprehension. The tuple is (value, month), but the f-string puts the month first. You choose the order and separator. Check the result, because the new name order can differ from the original column order.
Wait: the printed list above shows the order the columns are in after flattening, and it is not the order shown before. Reordering is not done by the code, so the real second line is:
['store', 'feb_sales', 'jan_sales', 'feb_units', 'jan_units']Columns keep their original positions. Only their names change.
Other ways to flatten
| Approach | Example | Use when |
|---|---|---|
| Join in a comprehension | `["_".join(map(str, c)) for c in df.columns]` | You want full control over the name |
| `to_flat_index` | `df.columns = df.columns.to_flat_index().map("_".join)` | All labels are already strings |
| `droplevel` | `df.columns = df.columns.droplevel(0)` | One level is redundant (for example, a single `values` column) |
| `get_level_values` | `df.columns = df.columns.get_level_values(1)` | You want one level and can discard the rest |
droplevel and get_level_values lose information. If two levels have different first-level labels but the same second-level label, you end up with duplicate column names. Duplicates make df["jan"] return a DataFrame instead of a Series, and some operations such as reset_index and merge raise errors on them. Check with df.columns.is_unique after flattening.
The whole pipeline
Common problems
- A name like
store_. You calledreset_indexfirst and joined an empty string. Flatten first, or filter empty parts. TypeError: sequence item 1: expected str instance, int found. A level holds numbers. Usemap(str, col).- A stray
monthlabel above the index. The column axis name is still set. Usecolumns.name = Noneorrename_axis(columns=None). ValueError: cannot insert ..., already exists. The index name matches an existing column. Rename one of them, or usedrop=Trueif the index is not needed.- Duplicate names after flattening. Choose a join pattern that keeps both levels.
- Unexpected column order. Pivoted columns come out sorted (
febbeforejan). Reorder withdf[["store", "jan", "feb"]]after flattening, orreindex(columns=[...])before you reset the index.
Summary
reset_index returns row labels to ordinary columns. Flattening replaces tuple column labels with strings you choose. Do the flattening first, or skip empty parts, and clear the leftover column axis name. After these steps, the pivot result behaves like any other DataFrame.
Exercise
You run sales.pivot_table(index="store", columns="month", values="sales", aggfunc=["sum", "mean"]) and want a flat table with the columns store, sum_feb, sum_jan, mean_feb, mean_jan. Write the two statements that produce it from the pivot result p, and say why their order matters.
Show answer
p.columns = ["_".join(map(str, c)) for c in p.columns] followed by p = p.reset_index(). Flattening first means every label is a tuple with two non-empty parts. If you call reset_index() first, the store column gets the tuple ("store", ""), and joining it gives store_ instead of store.
Exercise
After flattening with droplevel(0), df["jan"] returns a DataFrame with two columns instead of a Series. What happened, and how do you check for it?
Show answer
Two original columns had different first-level labels (for example sum and count) but the same second-level label jan. Dropping the first level left two columns both named jan. Check with df.columns.is_unique, which returns False, and fix it by joining both levels, for example "_".join(map(str, col)), instead of dropping one.