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
On this page
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
- Combine Batches with Schema DriftFiltering & Selection Medium
- Fit Conversations into a Context WindowData Prep for AI Hard
Keep going
Last lesson of PySpark functionsBack to the journey →
Related lessons
selectPySpark functions · 5 min read
dropDuplicatesData lake & lakehouse · 6 min read
Schema enforcement and evolution
Previous: unpivot
Primary sources: DataFrame.unionByName · Set operators (SQL)