Sub topic 2
Turning columns into rows with melt
This chapter assumes you can build a DataFrame, select columns with [] and loc, and read a groupby aggregation. It also assumes you know the wide and long layouts from the previous chapter. Here you will use DataFrame.melt to convert wide data to long data. You will also learn what it does to the index, to missing values and to data types.
What melt does
A wide table spreads one kind of measurement across several columns. For example, a monthly sales table has one column per month. A long table keeps one measurement per row, and a column records which month the row belongs to.
melt converts wide to long. It takes some columns and stacks them into two new columns:
- One new column holds the old column names, such as
janandfeb. - One new column holds the values that were under those names.
Columns you name as identifiers stay as they are. Their values repeat once for each stacked column.
The row count is the number of input rows multiplied by the number of melted columns. Two stores and two month columns give four rows. A table with 1,000 rows and 12 month columns gives 12,000 rows. Check this size before you melt a large table.
A first example
Start with a small wide table.
import pandas as pd
wide = pd.DataFrame({
"store": ["A", "B"],
"jan": [100, 80],
"feb": [110, 90],
})
long = wide.melt(id_vars="store", var_name="month", value_name="sales")
print(long)The output is:
store month sales
0 A jan 100
1 B jan 80
2 A feb 110
3 B feb 90The code does three things:
id_vars="store"keepsstoreas an identifier column. Its values repeat once per melted column.- Every column not named in
id_varsis melted. Here that meansjanandfeb. var_name="month"andvalue_name="sales"name the two new columns.
Pandas stacks the melted columns one after another. All the jan rows come first, then all the feb rows. Within each block the original row order is kept. The output is therefore not grouped by store. If you want it grouped, sort it afterwards:
print(long.sort_values(["store", "month"], ignore_index=True)) store month sales
0 A feb 110
1 A jan 100
2 B feb 90
3 B jan 80Sorting month as text puts feb before jan. Text sorts alphabetically, not by calendar order. Use an ordered categorical column if you need calendar order.
The default column names
If you leave out var_name and value_name, pandas uses variable and value.
default = wide.melt(id_vars="store")
print(default) store variable value
0 A jan 100
1 B jan 80
2 A feb 110
3 B feb 90These names say nothing about the data, so you should almost always set both. Meaningful names also make later groupby and plotting code easier to read.
There is one exception. If the columns Index has a name, melt uses that name for the variable column when you do not pass var_name.
named = wide.copy()
named.columns.name = "month"
print(named.melt(id_vars="store")) store month value
0 A jan 100
1 B jan 80
2 A feb 110
3 B feb 90The month label appears because named.columns.name is "month". The value column is still called value, because the Index name does not cover it.
What happens without id_vars
id_vars is optional. If you omit it, every column is melted, including text columns.
print(wide.melt()) variable value
0 store A
1 store B
2 jan 100
3 jan 80
4 feb 110
5 feb 90The result has six rows, which is 2 rows times 3 columns. The value column now mixes text and numbers, so pandas gives it the object dtype. Numeric work on it becomes awkward. The mixing is usually a sign that you forgot an identifier column.
The index after melt
By default, melt discards the old index and gives the result a fresh RangeIndex that starts at 0. In the first example the labels 0 to 3 are new. They do not come from wide.
That matters if the old index carried information, such as a store code or a date. In that case you have two choices. You can turn the index into a column before melting and name it in id_vars:
indexed = wide.set_index("store")
print(indexed.reset_index().melt(id_vars="store"))Or you can keep the original labels with ignore_index=False:
print(wide.melt(id_vars="store", ignore_index=False)) store variable value
0 A jan 100
1 B jan 80
0 A feb 110
1 B feb 90The index now repeats, because each original row appears once per melted column. A repeated index is legal but easy to misuse. loc[0] returns two rows. Alignment with other objects can also behave unexpectedly. Prefer an explicit identifier column unless you have a specific reason to keep the old labels.
Missing values are kept
melt does not drop missing values. Each cell in a melted column becomes a row, even if the cell is empty.
gaps = pd.DataFrame({
"store": ["A", "B"],
"jan": [100, 80],
"feb": [110, None],
})
long_gaps = gaps.melt(id_vars="store", var_name="month", value_name="sales")
print(long_gaps) store month sales
0 A jan 100.0
1 B jan 80.0
2 A feb 110.0
3 B feb NaNTwo things changed here. The empty feb cell for store B became a row with NaN. Also, None forced the feb column to float, so the combined sales column is float and the integers appear as 100.0.
Whether to keep the NaN row depends on what it means. If the cell means "no sale was recorded", you may want to remove the row. If it means "sales were unknown", you may want to keep the row so the gap stays visible. To drop these rows, filter after the melt:
print(long_gaps.dropna(subset=["sales"])) store month sales
0 A jan 100.0
1 B jan 80.0
2 A feb 110.0The row labels are not renumbered. The result jumps from 2 to the end with no label 3. Add ignore_index=True to dropna if you need a clean range.
Why long data is worth the extra rows
Long data looks more repetitive, but many pandas operations expect it. Once the months are values in a month column, a single groupby covers every month:
print(long.groupby("month")["sales"].sum())month
feb 200
jan 180
Name: sales, dtype: int64With the wide table you would write one expression for each month column, or loop over the column names. Adding a mar column to the wide table changes your code. After melting, a new month is just more rows, and the same groupby still works. Plotting libraries that map a column to colour or facets expect this layout as well.
Common mistakes
| Symptom | Likely cause | Fix |
|---|---|---|
| Columns named `variable` and `value` | `var_name` and `value_name` were left out | Pass both names |
| An identifier column appears as values under `variable` | It was not listed in `id_vars` | Add it to `id_vars` |
| The value column has dtype `object` | Text columns were melted with numeric ones | List the text columns in `id_vars` |
| Old index labels are gone | The default `ignore_index=True` replaced them | Move the index into a column first, or use `ignore_index=False` |
| Far more rows than expected | Many columns were melted | Check `len(df) * columns_melted` against `.shape[0]` |
| `KeyError` mentioning a column | A name in `id_vars` has a typo or different spacing | Compare against `df.columns.tolist()` |
The next chapter covers value_vars, which lets you melt only some of the non-identifier columns. For now, remember that without value_vars every column outside id_vars is melted.
Exercise
The DataFrame df has columns city, mon, tue and wed, with 5 rows. You run df.melt(id_vars="city", var_name="day", value_name="visits"). How many rows and columns does the result have, and what are its column names? What would change if you left out id_vars?
Show answer
The result has 15 rows (5 rows times 3 melted columns) and 3 columns, named city, day and visits. The mon, tue and wed names become the values of day, and their numbers become visits. Without id_vars, all four columns are melted. The result has 20 rows (5 times 4) and two columns, named variable and value unless you pass names. city would appear as values under variable, mixed with the day names. The value column would hold both city names and visit counts, so it would have the object dtype.
Exercise
A wide table has a numeric column feb where one cell is empty. After melt, you want a long table with no row for that empty cell and with the row labels numbered 0, 1, 2 and so on. Write the code after long = wide.melt(id_vars="store", var_name="month", value_name="sales").
Show answer
Use long = long.dropna(subset=["sales"], ignore_index=True). melt keeps the empty cell as a NaN row. dropna with subset=["sales"] removes rows where sales is missing. ignore_index=True renumbers the remaining rows from 0.