Merging DataFrames in pandas
Combine multiple tables with merge and concat — the pandas equivalent of SQL JOINs
Real data lives in multiple tables. Customer data is in one file, orders in another, products in a third. Merging combines them on a matching key — exactly like SQL JOINs.
pd.merge() is the SQL JOIN equivalent. pd.concat() stacks DataFrames vertically (appending rows) or horizontally (adding columns side by side).
Examples
Key Points
- ✓pd.merge(left, right, on="key") = SQL INNER JOIN by default
- ✓how="left" keeps all rows from the left DataFrame — most common in practice
- ✓pd.concat([df1, df2]) appends rows (axis=0 default) — use for combining monthly files
- ✓ignore_index=True resets the row index after concat — always use it
- ✓Validate merges: check len() before and after — unexpected rows = duplicate keys
Practice Question
You have a Sales DataFrame and a Products DataFrame. You want all sales records with product details added where available. Which merge type should you use?