Sub topic 10
Flattening columns and calling reset_index
This chapter assumes you can build a pivot_table and know what a MultiIndex is from the previous chapter. A reshaped table often has labels that are awkward to use. The row keys sit in the index instead of in columns. The column labels may have two levels, and the columns axis may carry a leftover name. Flattening fixes these problems so the result behaves like an ordinary DataFrame again.
What pivot leaves behind
Start with a pivot_table result.
import pandas as pd
sales = pd.DataFrame({
"store": ["A", "A", "B", "B"],
"month": ["jan", "jan", "jan", "feb"],
"sales": [60, 40, 80, 90],
})
wide = sales.pivot_table(
index="store", columns="month", values="sales", aggfunc="sum"
)
print(wide.index.name, wide.columns.name)The code prints store month. Two things stand out:
storeis the index, not a column. You cannot writewide["store"], and a merge or a CSV export treats it differently.- The word
monthis the name of the columns axis. It appears as a stray header above the column labels and is not a real column.
reset_index and rename_axis
reset_index() moves the index back into a regular column and creates a fresh 0, 1, 2... index. rename_axis(columns=None) removes the leftover axis name.
flat = wide.reset_index().rename_axis(columns=None)
print(flat.columns.tolist())The code prints ['store', 'feb', 'jan']. Setting flat.columns.name = None does the same job.
Flattening two-level columns
A list of aggregation functions gives two-level column labels. Each label is a tuple such as ("sum", "jan"). Join the parts of each tuple into one string, then restore the index.
multi = sales.pivot_table(
index="store",
columns="month",
values="sales",
aggfunc=["sum", "count"],
)
multi.columns = ["_".join(map(str, col)) for col in multi.columns]
multi = multi.reset_index()
print(multi.columns.tolist())The columns become store plus names such as sum_jan and count_feb. The order of operations matters:
- Flatten the columns while
storeis still the index. - Call
reset_index()last, sostorejoins the columns as a plain string.
If you reset the index first, store becomes a column whose label is ("store", ""). The join then produces store_.
Choosing a flattening style
| Technique | Use it when |
|---|---|
| `"_".join(map(str, col))` | You want one simple name per column. `map(str, ...)` protects against non-string labels such as integers. |
| `columns.to_flat_index()` | You want to keep the tuples and build names yourself, for example with an f-string. |
| `rename_axis(columns=None)` | The columns have a single level and only the axis name remains. |
Here is the second technique. It puts the aggregation name last, so sum_jan becomes jan_sum.
multi = sales.pivot_table(
index="store",
columns="month",
values="sales",
aggfunc=["sum", "count"],
)
multi.columns = [f"{month}_{func}" for func, month in multi.columns.to_flat_index()]
multi = multi.reset_index()
print(multi.columns.tolist())Common errors
- Totals produce trailing underscores. With
margins=True, the total column label has an empty second part, so a join givestotal_. Add.rstrip("_")to each joined name. - Duplicate column names after flattening. If two tuples join to the same string, later column selection returns several columns. Check with
multi.columns.is_unique. ValueError: cannot insert store, already exists. This appears whenstoreis already a column and you callreset_index(). Reset only once.
Exercise
A pivottable with aggfunc=["sum", "mean"] has columns like ("sum", "jan") and ("mean", "jan"), and store is the index. Write the two lines that give a flat DataFrame with store as a column and names such as sumjan.
Show answer
result.columns = ["".join(map(str, col)) for col in result.columns] result = result.resetindex() Flatten first, while store is still the index. Resetting first would give store a tuple label and a name like "store_".