Skip to content
Gold 4 min read · Selection 2 practice problems ↓

unionByName

Stack DataFrames by column name instead of position, and survive schema drift with allowMissingColumns.

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

Read first: select (skip if you know it)

In plain words first

Stacking two class registers, you would expect the "name" column of one to go under the "name" column of the other. union does not look at the headings at all: it puts the first column under the first column. If one register lists age first and the other lists name first, ages land under names.

unionByName reads the headings and lines the columns up correctly.

Unlock the full lesson

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

  • Position vs name
  • Step by step
  • Run the example
  • union is UNION ALL
  • 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 unionByName, graded on hidden tests

See all 4 problems →

Keep going

Last lesson of PySpark functions
Back to the journey →

Related lessons

Previous: unpivot

Primary sources: DataFrame.unionByName · Set operators (SQL)