Data analysis · Intermediate · 18 min
Reshape data between wide and long with pivot and melt
By Padding · Updated 18 Nov 2026
Python 3.15 · pandas 3.1.1 · uv 0.13 (checked on python:3.15-slim)
You will turn a one-column-per-month spreadsheet export into long, tidy rows with pandas 3.1 and back again, handle duplicate entries with pivot_table, compute shares with crosstab and move between shapes with stack and unstack.
On this page
Most data that people send you is wide. A sales report has one row per shop and one column per month, because that is how a person reads it: across a row to see a shop's year, down a column to compare shops. Most analysis code wants the data long, with one row per shop per month and the month as a value in its own column. Filtering, grouping and most chart libraries work on that shape without extra effort.
Moving between the two is called reshaping. pandas has a small set of tools for it: melt makes data long, pivot makes it wide, pivot_table and crosstab make it wide while summarising, and stack and unstack do the same moves on a MultiIndex. This tutorial uses all of them on one small export: mobile data bundle sales for four shops in Lagos, Nairobi and Accra over four months. One shop missed a month, which is the kind of gap that reshaping can hide or expose depending on how you do it.
Everything happens in a throwaway folder, ~/reshape-demo, which the last step removes.
Step 1 · Create the project and the wide export
Create the project and add pandas. The version range allows bug-fix releases of 3.1 and nothing newer:
mkdir -p ~/reshape-demo
cd ~/reshape-demo
uv init --no-package --python 3.15
uv add "pandas>=3.1,<3.2"Now write the export. In practice this is the CSV you download from a sales dashboard or save from a spreadsheet. Kasoa's February cell is empty because the shop sent no figure that month:
cat > bundles_wide.csv <<'CSV'
shop,city,Jan,Feb,Mar,Apr
Ikeja,Lagos,120,135,150,160
Yaba,Lagos,90,85,110,95
Westlands,Nairobi,200,210,190,230
Kasoa,Accra,60,,75,80
CSV
uv run python -c "import pandas as pd; w = pd.read_csv('bundles_wide.csv'); print(w.shape); print(w.dtypes.to_string())"Notice the types. Jan, Mar and Apr are whole numbers, int64, but Feb is float64. pandas marks the empty cell as NaN, and NaN is a floating-point value, so the whole column becomes float. That one blank is already changing how the data behaves.
Check it worked
The command prints (4, 6): four shops and six columns. In the type list, shop and city are str, Jan, Mar and Apr are int64, and Feb is float64.
Step 2 · Melt the month columns into rows
melt takes columns and turns them into rows. You tell it which columns identify a row and stay as they are (id_vars), which columns to fold down (value_vars), and what to call the two new columns: one for the old column headers (var_name) and one for the values that were in the cells (value_name).
Put the reshaping in a small module, tidy.py, so the later steps all start from the same long table. After melting, it does three more things:
- Drops rows with no value. A missing month in wide form is an empty cell; in long form it is a row that says nothing, so remove it.
- Makes
monthan ordered categorical. As plain text, months sort alphabetically: Apr, Feb, Jan, Mar. A categorical keeps calendar order everywhere the column goes. - Turns
unitsback into whole numbers, now that noNaNis left.
cat > tidy.py <<'PY'
import pandas as pd
MONTHS = ["Jan", "Feb", "Mar", "Apr"]
def load_long():
wide = pd.read_csv("bundles_wide.csv")
long = wide.melt(
id_vars=["shop", "city"],
value_vars=MONTHS,
var_name="month",
value_name="units",
)
long = long.dropna(subset=["units"])
long["month"] = pd.Categorical(long["month"], categories=MONTHS, ordered=True)
long["units"] = long["units"].astype("int64")
return long.sort_values(["shop", "month"]).reset_index(drop=True)
PY
cat > melt_it.py <<'PY'
import pandas as pd
from tidy import MONTHS, load_long
wide = pd.read_csv("bundles_wide.csv")
raw = wide.melt(
id_vars=["shop", "city"], value_vars=MONTHS, var_name="month", value_name="units"
)
print("raw long:", raw.shape)
print(raw.head(5).to_string())
print()
long = load_long()
print("tidy long:", long.shape)
print(long.dtypes.to_string())
PY
uv run melt_it.pyFour shops times four months gives 16 rows. Dropping Kasoa's empty February leaves 15. The raw result lists all of January first, then all of February, because melt walks the month columns one at a time. The sort in load_long groups each shop's months together, which is easier to read.
If you leave out value_vars, melt folds every column not named in id_vars. That is convenient until someone adds a notes column to the export and it turns up as a month. Naming the columns makes the script fail loudly instead.
Check it worked
The raw result is (16, 4) and starts with Ikeja, Yaba, Westlands and Kasoa for Jan, then Ikeja for Feb with 135.0. The tidy result is (15, 4), with month as category and units as int64.
Step 3 · Pivot back to wide and prove nothing was lost
pivot is the reverse of melt. index names the columns that become row labels, columns names the column whose values become the new headers, and values fills the cells. A round trip back to the original is a cheap way to prove that a reshape lost nothing:
cat > pivot_back.py <<'PY'
import pandas as pd
from tidy import load_long
long = load_long()
back = long.pivot(index=["shop", "city"], columns="month", values="units")
print(back)
print()
back = back.reset_index().rename_axis(columns=None).sort_values("shop").reset_index(drop=True)
original = pd.read_csv("bundles_wide.csv").sort_values("shop").reset_index(drop=True)
pd.testing.assert_frame_equal(back, original, check_dtype=False, check_column_type=False)
print("round trip matches the original")
PY
uv run pivot_back.pyThe month columns come out in calendar order because month is categorical. Kasoa's February returns as NaN: there is no row for it, so pivot has nothing to put in that cell. All the counts are floats again for the same reason as before.
pivot returns shop and city as a two-level row index, with month as the name of the column axis. reset_index turns the row labels back into ordinary columns and rename_axis(columns=None) drops the month label, so the table has the same layout as the CSV. assert_frame_equal raises an error if any value differs. check_dtype=False lets the float columns match the original's whole numbers.
Check it worked
The printed table has Jan, Feb, Mar and Apr in that order, Kasoa's row reads 60.0 NaN 75.0 80.0, and the last line is round trip matches the original.
Step 4 · See pivot fail on duplicates and use pivot_table
pivot only rearranges values; it never adds them up. If two rows share the same index and columns pair, it cannot choose one, so it raises an error. This happens often in practice: a late sale typed in as a separate row, or two exports appended together.
Add a late entry of 10 units for Ikeja in January and try again:
cat > duplicates.py <<'PY'
import pandas as pd
from tidy import load_long
long = load_long()
late = pd.DataFrame({"shop": ["Ikeja"], "city": ["Lagos"], "month": ["Jan"], "units": [10]})
late["month"] = pd.Categorical(
late["month"], categories=long["month"].cat.categories, ordered=True
)
long = pd.concat([long, late], ignore_index=True)
try:
long.pivot(index="shop", columns="month", values="units")
except ValueError as err:
print("pivot failed:", err)
print()
dupes = long[long.duplicated(subset=["shop", "month"], keep=False)]
print(dupes.to_string())
print()
table = long.pivot_table(
index="shop", columns="month", values="units", aggfunc="sum", observed=True
)
print(table)
PY
uv run duplicates.pyBefore you reach for pivot_table, find out why the duplicates exist. duplicated(keep=False) marks every row in a clash, not only the second one, so you see both. If the late row is a real extra sale, adding it is right. If it is the same sale entered twice, adding it double-counts, and you should remove the copy instead.
Here the sale is real, so pivot_table with aggfunc="sum" adds the two January rows. pivot_table groups first and reshapes second, which is why it accepts duplicates. Choose the aggregate on purpose: "sum" for counts and money, "mean" for readings such as temperatures, "last" for a value that was corrected. observed=True limits the output to month categories that appear in the data; it is the default in pandas 3, and writing it out makes the intent clear.
Kasoa's February is still NaN, not 0. No figure was sent, which is different from selling nothing. Add fill_value=0 only when a missing combination really means zero.
Check it worked
The first line is pivot failed: Index contains duplicate entries, cannot reshape. The duplicates table shows two Ikeja January rows, with 120 and 10 units. In the final table Ikeja's January reads 130.0 and Kasoa's February is still NaN.
Step 5 · Count and compute shares with crosstab
crosstab builds a frequency table: how many rows fall into each pair of categories. With values and aggfunc it sums instead of counting, and normalize turns the result into shares. normalize="columns" makes each column add up to 1, "index" does the same for each row, and "all" divides by the grand total.
cat > shares.py <<'PY'
import pandas as pd
from tidy import load_long
long = load_long()
print(pd.crosstab(long["city"], long["month"]))
print()
share = pd.crosstab(
long["city"], long["month"], values=long["units"], aggfunc="sum", normalize="columns"
)
print(share.round(3))
print()
print(share.sum().round(3).to_string())
PY
uv run shares.pyRead the two tables together. The count table shows how many shop reports each city sent per month: Lagos has two shops, and Accra has a 0 in February. The share table says what part of each month's units came from each city. In January, Accra's 60 units out of 470 is 0.128.
Accra's February share prints as 0.000, which looks like "sold nothing". The count table shows the real reason: no report arrived. Shares are only comparable across months when every shop reported, so check the counts before you put the shares in a chart or a slide.
Check it worked
The count table has Accra 1 0 1 1 and Lagos 2 2 2 2. The share table's Accra row reads 0.128 0.000 0.143 0.142, and each month in the last list sums to 1.0.
Step 6 · Stack and unstack with a MultiIndex
set_index with several columns gives a MultiIndex: each row is labelled by a tuple, such as ("Lagos", "Ikeja", "Jan"). On that shape, unstack moves the innermost level (or the level you name) from the rows into the columns, making it wider. stack moves the column labels back into the rows. They are pivot and melt for data that is already indexed, and they are handy after a groupby, which returns a MultiIndex when you group by two keys.
cat > stack_it.py <<'PY'
from tidy import load_long
long = load_long()
units = long.set_index(["city", "shop", "month"])["units"]
print(units.index.nlevels, "levels,", len(units), "values")
wide = units.unstack("month")
print(wide)
again = wide.stack()
print(len(again), "values after stack,", len(again.dropna()), "after dropna")
print()
by_city = long.groupby(["city", "month"], observed=True)["units"].sum().unstack("month")
print(by_city)
PY
uv run stack_it.pyOne change in pandas 3 matters here. stack used to drop missing values on the way back to long form. It now keeps them, so the round trip gives 16 values, including Kasoa's empty February. Add .dropna() when you want the gaps gone, as load_long does after melt.
The last table is a common pattern: group by two keys, sum, then unstack one key into columns. It gives the same result as pivot_table(index="city", columns="month", values="units", aggfunc="sum"). Use whichever reads better in your script.
Check it worked
The first line is 3 levels, 15 values. The wide table has city and shop down the side, with Kasoa's row reading 60.0 NaN 75.0 80.0. Next comes 16 values after stack, 15 after dropna, and in the city table Lagos reads 210.0 220.0 260.0 255.0.
Step 7 · Give each tool the shape it expects
Before you hand data to another library, check which shape it wants:
- seaborn, plotly express and Altair work best with long data. You name columns for each role, such as
x="month",y="units"andhue="shop", and the library splits the lines or bars for you. Some also accept wide data, but long data gives you control over which column does what. DataFrame.plotin pandas draws one line per column, so it wants wide data: months as the index and one column per shop.- scikit-learn and most other model libraries want a wide feature matrix: one row per sample and one column per feature, with no missing values.
Write both from the same long table:
cat > shapes.py <<'PY'
from tidy import load_long
long = load_long()
# Long: one row per shop and month, for seaborn, plotly express or Altair
long.to_csv("for_charts.csv", index=False)
print("for_charts.csv:", long.shape, list(long.columns))
# Wide: one row per shop, one column per feature, for a model
features = (
long.pivot(index="shop", columns="month", values="units")
.rename(columns=str)
.add_prefix("units_")
.rename_axis(columns=None)
)
print("missing feature values:", int(features.isna().sum().sum()))
features = features.interpolate(axis="columns")
print("features:", features.shape, list(features.columns))
print(features)
PY
uv run shapes.pyA model cannot take a NaN, so the gap has to be filled, and how you fill it is an analysis decision. Filling with the column mean would give Kasoa about 143 units in February, more than double its usual level, because the mean is pulled up by the bigger shops. interpolate(axis="columns") fills along each shop's own row instead, halfway between January's 60 and March's 75, giving 67.5. Record whichever choice you make next to the result.
Long files are also easier to send. A long CSV gains rows, not columns, as months are added, and exports keep the same layout every month. If you share files over a prepaid mobile connection, compress the CSV (gzip for_charts.csv): repeated shop and city names compress well.
When you have finished, remove the demo project. Python and uv stay installed:
cd ~
rm -rf ~/reshape-demoCheck it worked
Before the clean-up, the script prints for_charts.csv: (15, 4) with the four long column names, then missing feature values: 1, then features: (4, 4) with units_Jan to units_Apr. Kasoa's row in the feature table reads 60.0 67.5 75.0 80.0. After the clean-up, ls ~/reshape-demo reports that the folder does not exist.
Next steps
- Summarise long data by several keys at once, and add group totals back to each row: group and aggregate data in pandas.
- If you came from spreadsheets, see how a pivot table and SUMIFS map to pandas: move from spreadsheet formulas to pandas.
- Do the same reshaping in SQL with PIVOT and UNPIVOT: write analyst SQL with DuckDB shortcuts.
- Chart the long table with
hue=: make statistical charts with seaborn.
Part of these paths
Related tutorials
- Group and aggregate data in pandasYou will summarise a shop's sales by region, month and city with pandas groupby, named aggregation, transform and filter, and finish with a regional report whose totals you have checked against the raw data.
- Move from spreadsheet formulas to pandasYou will redo a shop's sales workbook in pandas 3.1, step by step, turning fill down, XLOOKUP, IF, filters, SUMIFS, COUNTIFS and a pivot table into a short Python script that writes its results back to Excel.
- Write shorter analyst SQL with DuckDB's friendly extensionsYou will profile, group, filter, reshape and join a small sales dataset with eight DuckDB extensions to SQL, each run next to the standard query it replaces, and know which ones will not carry over to another database.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials