Module 3 · pandas · Lesson 20 of 66

Combining tables

Stack tables with concat, and match them up with merge and join.

In this lesson · about 16 minutes

  • Stack DataFrames with pd.concat
  • Merge on a key column, like a SQL join
  • Know inner, outer, left and right joins

Data often arrives in pieces. There are three main ways to put it together:

  • Concatenate glues tables end to end: pd.concat([df1, df2]) stacks rows; axis=1 puts them side by side. The shapes should match along the joining side.
  • Merge matches rows that share a key value, like a SQL join: pd.merge(left, right, on='key').
  • Join is a shortcut for merging on the index: left.join(right).

Merge and the four kinds of join

how=Keeps
'inner' (default)Only keys found in both tables
'outer'Every key from either table, with NaN where one side is missing
'left'Every key in the left table
'right'Every key in the right table

Join on the index

Exercise

Every customer, with their orders

Merge customers and orders on id so that every customer appears, even Ben, who has no orders.

Code that runs before yours
import pandas as pd
customers = pd.DataFrame({'id': [1, 2, 3], 'name': ['Ana', 'Ben', 'Chen']})
orders = pd.DataFrame({'id': [1, 1, 3, 4], 'amount': [25, 40, 15, 60]})

Exercise

Stack two months

Stack jan and feb into one table with pd.concat, numbering the rows 0 to 3 by passing ignore_index=True.

Code that runs before yours
import pandas as pd
jan = pd.DataFrame({'item': ['tea', 'cake'], 'sold': [30, 12]})
feb = pd.DataFrame({'item': ['tea', 'cake'], 'sold': [41, 9]})

Check your understanding0 of 1 correct

Question 1

1.In the customers/orders merge above, why is id 4 missing from the inner merge?

Quiz score: 0 of 1

Exercises solved: 0 of 2

Tip: answer every quiz question correctly first.

Noviq Academy's Data Science course is free and for learning. Python runs in your browser with Pyodide, which downloads about 20 MB the first time, plus a few more for scikit-learn. Your code and progress stay on this device. The salaries data is a sample of San Francisco's public pay records; the purchases, customers, housing, advertising and classified data are made up. The Titanic, tips, flights and iris data sets come from Seaborn's examples; the maps use public 2011 to 2014 US and world figures. The 911 data is a 20,000-call sample of Montgomery County, Pennsylvania's public 911 records; the movie ratings are the MovieLens 100K data from GroupLens Research; the reviews are a 3,000-review sample from the Yelp Dataset Challenge; the loans are public LendingClub data; the colleges are the College data from An Introduction to Statistical Learning; the bank notes, kyphosis and breast cancer data come from the UCI Machine Learning Repository. Spark and TensorFlow can't run in a browser, so those lessons use stand-ins that run here, and show the code for the real tools.