Python Essentials for Data Analytics
Back to PANDAS FOR DATA ANALYTICS

Combining DataFrames: SQL-Style Relational Merges

Master relational database-style joins in Pandas using pd.merge(): inner, outer, left, and right joins, join keys, indicator flags, and custom suffixes.

8 minutesVideo LessonPDF notes
🎯 Free Guest Mode: You are learning for free. Sign in to save your completion progress and quiz answers.
Loading progress...

Key moments

  1. Setup and Goal — The instructor introduces two DataFrames (temperature and humidity) and the goal of combining them into a single table.
  2. Basic pd.merge() — The basic syntax for `pd.merge()` is shown, demonstrating that it matches data by key value (`city`) rather than row index.
  3. Inner Join Default — The default behavior is shown to be an inner join (intersection), keeping only the keys common to both DataFrames.
  4. Outer Join (Union) — The `how='outer'` argument is introduced to perform a union, preserving all keys and filling non-matching columns with NaN.
  5. Left and Right Joins — Left join preserves all rows from the first DataFrame, while right join preserves all rows from the second DataFrame.
  6. Tracking Row Origin — Setting `indicator=True` adds the `_merge` column, which specifies if a row originated from the left, right, or both DataFrames.
  7. Handling Column Conflicts — When non-key columns are repeated, Pandas automatically appends `_x` and `_y` suffixes to distinguish them.
  8. Custom Suffixes — The `suffixes` argument is used to override the default `_x` and `_y` with custom, descriptive labels.
PDF notes

Frequently asked questions

What is the default join type if I don't specify `how`?

The default is `how='inner'`, which only returns rows where the key exists in both DataFrames (intersection).

Why do I see `NaN` values in my merged DataFrame?

`NaN` appears when you use an outer, left, or right join, and a row from one table has no matching key in the other table.

How can I tell which DataFrame a specific row came from after an outer merge?

Set `indicator=True` in the `merge` call; this adds a column named `_merge` showing 'left_only', 'right_only', or 'both'.

If both DataFrames have a 'temp' column, how does Pandas handle the conflict?

Pandas automatically appends `_x` to the left column and `_y` to the right column, unless you specify custom suffixes.

How was this lesson?

Your feedback helps us refine explanations and catch bugs.