Sub topic 2
Turning columns into rows with melt
This chapter assumes you can create a pandas DataFrame, select columns with [] and loc, and have used groupby with aggregations such as sum. Here you will learn how melt converts a wide table into a long one.
Why melt exists
A wide table spreads one kind of measurement across several columns. In the example below, each month has its own column. Most pandas tools, including groupby, plotting libraries and pivot, work best when each variable has one column and each observation has one row. That is the long layout.
DataFrame.melt is the "unpivot" operation. It keeps some columns fixed as identifiers and stacks the remaining columns into two new columns: one holding the old column names, and one holding the values.
A first melt
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 has four rows:
store month sales
0 A jan 100
1 B jan 80
2 A feb 110
3 B feb 90The two input rows and two month columns give four observations. Each store and month pair now has its own row.
How the pieces map
The three arguments control the shape of the result.
| Argument | Role | In the example |
|---|---|---|
| `id_vars` | Columns kept as identifiers and repeated for each stacked column | `store` |
| `var_name` | Name of the new column that holds the old column labels | `month` |
| `value_name` | Name of the new column that holds the cell values | `sales` |
If you omit var_name and value_name, pandas names the new columns variable and value. Those names are rarely meaningful, so set them explicitly.
Row order
melt stacks one original column at a time. All the jan rows come first, then all the feb rows. The original index is not kept by default, and the result gets a fresh 0..n-1 index. If you need the original index, pass ignore_index=False. The index values then repeat, once per stacked column.
What melt does when you leave arguments out
If you give id_vars but not value_vars, pandas treats every other column as a value column. That is convenient here, but it can go wrong when the frame has extra columns you did not intend to stack. For example, a region column would be melted into sales and mix text into a numeric column. When a frame has columns beyond the ones you want, name the value columns explicitly with value_vars. The next chapter covers this in detail.
If you give neither argument, every column is stacked and no identifier is kept. That is rarely what you want.
Common errors
- Mixed types in the value column. If you stack numeric and text columns together, the
valuecolumn becomesobjectdtype. Checklong.dtypesafter a melt. - Forgetting identifier columns. If a column that identifies the row is not in
id_vars, it is stacked as a value and you lose the link between rows and their keys. - Misspelled column names.
id_vars="Store"when the column isstoreraises aKeyError. Column names are case sensitive. - Expecting the original order. The result is ordered by stacked column first, not by original row. Sort with
sort_values(["store", "month"])if you need row order.
Checking the result
A quick sanity check is that the number of output rows equals the number of input rows multiplied by the number of stacked columns. Here that is 2 × 2 = 4. If the count differs, a column was stacked or left out unintentionally.
n_value_cols = len(wide.columns) - 1
assert len(long) == len(wide) * n_value_cols
print(long.dtypes)Exercise
A DataFrame has columns city, mon, tue and wed, with 5 rows. You call df.melt(id_vars="city", var_name="day", value_name="visits"). How many rows and which columns does the result have?
Show answer
The result has 15 rows (5 rows × 3 stacked columns) and three columns: city, day and visits. The day column holds mon, tue and wed, and visits holds the original cell values.
Exercise
Why is it risky to call melt(id_vars="store") on a frame that also has a text column named region?
Show answer
Without value_vars, every column other than store is stacked, including region. Its text values end up in the same value column as the numbers, so the column gets object dtype. Pass value_vars=["jan", "feb"] to stack only the intended columns.