Merging DataFrames
Combine DataFrames with merge and concat — the Pandas equivalent of SQL JOINs
Merging is how you combine data from multiple tables. Pandas merge() works exactly like SQL JOINs. concat() stacks DataFrames vertically or horizontally. These are essential when your data comes from multiple files or sources and needs to be combined before analysis.
Examples
Key Points
- ✓merge() is SQL JOIN — default is inner join, how= controls left/right/outer
- ✓Always check the row count before and after merge to detect unexpected fan-out
- ✓concat() with ignore_index=True resets index to 0,1,2... — almost always what you want
- ✓validate="one_to_many" in merge() raises an error if the join produces unexpected duplicates
- ✓suffixes=("_left", "_right") handles columns with the same name in both tables
Practice Question
You have an Orders table and a Customers table. You want ALL orders, with customer details where available (nulls where no customer match). Which merge type?
Related Topics
Pandas DataFramesThe core Pandas data structure — a 2D table with rows and columnsgroupby and Pivot TablesAggregate data by category with groupby — the Pandas equivalent of Excel pivot tablesSQL with Python — pandas and SQLiteQuery databases directly from Python using pandas and run SQL on DataFrames with DuckDB