pandas in depth · lesson 3 of 12
Parts in this lesson
Aa.merge(b, on="store", how="left")add b’s columns to a’s rows
Bindicator=Truesay where each row came from
Cvalidate="many_to_one"fail if the key repeats on the right
Dpd.concat([jan, feb])one table under another

Joining tables

Last updated

Real data comes in several tables: sales in one, stores and their towns in another, prices in a third. To answer most questions you have to put them together. In this lesson you'll join tables on a key with merge, stack tables with concat, and use the two arguments that stop a join from quietly doubling your totals.

By the end of this lesson you can

  • Join two tables on a key with merge
  • Choose between inner, left and outer joins, and say what each drops
  • Stack tables with concat
  • Catch a join that multiplies rows, with validate

Keys and the four joins

A key is a column two tables share, which says which row of one goes with which row of the other. Here it's the store name. Step through the joins:

Two tables joined on a key. Two tables share a key, the store name. One has kilos, the other has towns. Rosario is only on the left; Nasugbu only on the right.Batangas103Lipa87Tanauan74Rosario24BatangasBatangas CityLipaLipa CityTanauanTanauan CityNasugbuNasugbutotalsstorekilosstoresstoretown
1 of 4 Two tables share a key, the store name. One has kilos, the other has towns. Rosario is only on the left; Nasugbu only on the right.
join.ipynb
  • how="inner", the default, keeps keys found in both: three stores. Rosario's 24 kg have gone, silently. That's the danger of the default.
  • how="left" keeps every row of the left table. Rosario stays, with NaN for its town. Use it when the left table is the thing you're counting (sales) and the right one only adds details (towns). It never loses a sale.
  • how="outer" keeps everything from both. indicator=True adds a _merge column saying where each row came from: both, left_only or right_only. It's the quickest way to see what didn't match, and why.
  • (how="right" is left the other way round. You'll rarely need it.)

Notice opened became 2015.0: the NaNs a join adds make whole numbers floats, as in lesson 3.7.

Check the row count after every join. If it went down, an inner join dropped something; if it went up, read step 3.

Stacking tables

Each month's sales arrive as a separate file, with the same columns. pd.concat puts them one under another. Run it.

months.ipynb

ignore_index=True numbers the rows 0 to 3 again; without it, you'd have two rows labelled 0 and two labelled 1. merge puts tables side by side, matching keys; concat puts them end to end, matching column names. A column missing from one file becomes NaN in its rows.

Wrong way: the join that doubled the sales

The price list has a price for each item, and a date it started: rice went up on 15 January, so rice has two rows. Join it to the sales by item. Run the cells.

prices.ipynb

12 rows became 18, and the kilos sold went from 264 to 471. No error. Each rice sale matched both rice prices, so every rice row was copied. Anything you work out from joined, a revenue total, an average, is wrong, and nothing on screen says so.

The join was meant to be many-to-one: many sales for each item, one price per item. Saying so with validate="many_to_one" turns the silent copying into a MergeError the moment it happens. The fix itself is a question about the data: here you'd pick each sale's price by its date (a job for pd.merge_asof), or keep only the current price.

Kinds of join, by how often the key repeats on each side:

validatemeansexample
"one_to_one"each key once on each sidestores and their managers
"many_to_one"repeats on the left onlysales and stores
"one_to_many"repeats on the right onlystores and their sales

Give validate on every join you write. It costs one argument, and turns a wrong total into an error.

Check what you learned

Sales has 1,000 rows. You join it to a store list with an inner join and get 940. What happened?
You have January’s and February’s sales in two tables with the same columns. How do you make one table?
After joining sales to a price list, total kilos went up. What should you have passed to merge?

Sources

Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.

All sources for Simple Data Analysis