Initializing playground…
← Back to roadmap

🔄 stack / unstack — Interactive Playground

Pivot column labels into the row index and back — mirrors pandas.DataFrame.stack() and pandas.Series.unstack().
Edit any code block below and press ▶ Run (or Ctrl+Enter) to execute it live in your browser.

1 · Basic stack

stack(df) rotates column labels into the row index, producing a flat Series. Index labels take the form "rowLabel|colName".

TypeScript
Click ▶ Run to execute
Ctrl+Enter to run · Tab to indent

2 · stack drops null by default

Like pandas, stack() silently omits cells whose value is null or NaN. Pass { dropna: false } to keep them.

TypeScript
Click ▶ Run to execute
Ctrl+Enter to run · Tab to indent

3 · unstack: recover the original DataFrame

unstack(s) is the inverse of stack(df, { dropna: false }). It parses the compound index labels and reconstructs the grid.

TypeScript
Click ▶ Run to execute
Ctrl+Enter to run · Tab to indent

4 · unstack fills missing cells

When stack was called with dropna=true (the default), some (row, col) combinations are absent. unstack fills them with null by default; pass fill_value to use a different filler.

TypeScript
Click ▶ Run to execute
Ctrl+Enter to run · Tab to indent

5 · Custom separator

If your row-index labels or column names contain "|", choose a different separator for both stack and unstack.

TypeScript
Click ▶ Run to execute
Ctrl+Enter to run · Tab to indent

6 · Reshape workflow: stack → filter → unstack

A common pattern: stack to long format, filter rows, then unstack back to wide.

TypeScript
Click ▶ Run to execute
Ctrl+Enter to run · Tab to indent

API Reference

The compound index uses a separator (default "|") to join row labels and column names. Use .index.values and .values to inspect the stacked Series.

// Stack — DataFrame → Series
stack(df, {
  dropna?: boolean,  // default true  — omit null/NaN cells
  sep?:    string,   // default "|"   — row|col separator
}): Series

// Unstack — Series → DataFrame
unstack(series, {
  fill_value?: unknown,  // default null — fill missing cells
  sep?:        string,   // default "|"  — separator to split index
}): DataFrame