Skip to content
Learn Netverks

Lesson

Step 20/36 56% through track

pivot-melt

Pivot and melt

Last reviewed May 28, 2026 Content v20260528
Track mode
server_script
Means
Server runner
Reading
~1 min
Level
intermediate

This lesson

This lesson teaches Pivot and melt: Pandas tabular manipulation—indexing, dtypes, reshaping, and analysis habits for real-world tables.

Teams apply Pivot and melt in every serious Pandas project—skipping it leaves blind spots in analysis and reviews.

You will apply Pivot and melt in contexts like: Cohort KPIs, funnel breakdowns, and executive summary tables.

Read the narrative, run `import pandas as pd` snippets with in-memory DataFrames (install pandas and numpy with pip if needed), inspect `.head()`, `.dtypes`, and complete MCQs.

When you can explain the previous lesson's ideas in your own words.

pivot / pivot_table widen data (long → wide); melt tidies data (wide → long). Essential for report-style tables and tidy-data pipelines.

pivot_table

import pandas as pd
df = pd.DataFrame({'date': ['Jan','Jan','Feb'],
                   'product': ['A','B','A'],
                   'sales': [10, 20, 15]})
wide = df.pivot_table(index='date', columns='product',
                      values='sales', aggfunc='sum', fill_value=0)
print(wide)

melt

long = wide.reset_index().melt(id_vars='date',
                             var_name='product', value_name='sales')
print(long)

When to use

  • pivot_table — cross-tab summaries with aggregation (handles duplicates)
  • pivot — strict reshape when index/column pairs are unique
  • melt — stack columns into variable/value pairs for plotting or modeling

Important interview questions and answers

  1. Q: pivot vs pivot_table?
    A: pivot_table aggregates duplicates; pivot errors on duplicate index/column keys.
  2. Q: Tidy data?
    A: One row per observation—melt helps convert wide spreadsheets to tidy form.

Self-check

  1. Create a pivot_table of sales by date and product.
  2. Melt a wide table back to long format.

Pitfall: Use pivot_table when duplicate index/column pairs exist—strict pivot errors.

Interview prep

pivot_table vs pivot?

pivot_table aggregates duplicates; strict pivot errors on dup keys.

melt?

Wide to long—tidy data for modeling and plotting.

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Playground

Runs on the configured server runner (dev: npm run runner with LEARNING_RUNNER_ENABLED=true). Output appears below the editor.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • wide vs long?
  • melt id_vars?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump