Skip to content
Gold 3 min read · Reshaping 3 practice problems ↓

unpivot

Turn columns into rows (wide to long) with unpivot or the SQL stack() function.

Step 1 · PySpark functions · Gold · Gold reshaping patterns, lesson 2 of 3

Read first: pivot (skip if you know it)

In plain words first

A sales grid has regions down the side and quarters across the top. To ask "total per quarter" you would need a sum per column. Cut the grid into one card per cell instead, each saying "region, quarter, amount", and every question becomes a simple filter or group.

That is unpivoting: the opposite of pivotpivot: Turn the values of one column into column headings, with an aggregate in each cell. Learn more →.

Unlock the full lesson

You have read the free part. The rest of this advanced lesson:

  • What it does
  • Step by step
  • Run the example
  • Nulls
  • Before 3.4: stack()
  • Types
  • Under the hood
  • Common mistakes
  • Key takeaways
  • Interview prep with 3 follow-up questions
  • Check yourself: 3 questions

Unlock it with the Complete pass (every advanced problem and lesson) or on its own.

Practise this

Problems that use unpivot, graded on hidden tests

Keep going

Up next · Gold reshaping patterns · lesson 3 of 3 · 4 min read
unionByName
Stack DataFrames by column name instead of position, and survive schema drift with allowMissingColumns.

Related lessons

Previous: rollup / cube

Primary sources: DataFrame.unpivot · UNPIVOT clause