Skip to learning content

DATA SCIENCE PYTHON PLAYGROUND

Data Foundations · A little practice goes a long way.

← Wrangle / Preprocess lessonsTINY TABLES · REAL PYTHON · YOUR PACE
Groups & reshaping · W24 · 8 MIN

Combine tables by keys

Join a lookup table while checking the relationship.

Exercises within this concept

  1. FollowFollow the techniqueCurrent exercise
  2. ChangeKeep matches only
  3. TransferChoose and combine

Understand the idea

merge attaches fields by matching a key. The join type decides what happens to records without a match.

Concept sketch: left join: keep unmatched rows tookeyvalueA2B4keyvaltagA2yesB4NaNlookup: A → yesleft join: keep unmatched rows too
Illustration · not the exercise output

A small example

If left keys are A, B and lookup has only A: a left join keeps A and B; an inner join keeps only A.

Follow the code

Apply the idea to the supplied table. Read from top to bottom; the final line displays the result.

df.merge(lookup, on="flavour", how="left", validate="many_to_one")

What each part does

on="flavour"
Match rows on equal flavour values in both tables.
how="left"
Keep every df row; unmatched lookup values become missing.
validate="many_to_one"
Allow repeated flavours in df but require each flavour to appear only once in lookup.
Other choices for later exercises
how="inner"
Keep only rows with matches on both sides instead.

Your inputs

The editable setup on the right creates df and the additional inputs shown below. Run executes the setup and your work from top to bottom.

Candy shop · 6 synthetic rows
candyflavourpriceratingshelf
Gummy Bearfruity1.24.1A
Choco Popchocolate2.14.6B
Mint Bitemint1.53.8A
Berry Loopfruity2.84.4B
Cocoa Cubechocolate3.44.9A
Lemon Dropfruity1.84B
lookup · given lookup
flavourpriority
fruity1
chocolate2

Your task · Follow

  1. Left-join lookup onto df on flavour; retain every df row and use validate="many_to_one".
  2. Return the joined DataFrame.
  3. Use: merge().
Hint

A left join retains unmatched observations; validate checks that the lookup key is unique.

Reveal solution

One way to do it. Keep any supplied setup in the editor and use this in the Your work section.

df.merge(lookup, on="flavour", how="left", validate="many_to_one")
Your task · Follow
  1. Left-join lookup onto df on flavour; retain every df row and use validate="many_to_one".
  2. Return the joined DataFrame.
  3. Use: merge().

Tab: indent · Shift+Tab: outdent · Esc, then Tab: leave editor

Edit Python. Control or Command plus Enter runs it. Tab indents by four spaces. Shift plus Tab outdents. Press Escape, then Tab or Shift plus Tab to leave the editor.

Each run executes all editor code in a fresh Python session. Display a value by leaving it on the final line.

Python starts when you open a lesson.

Output

Run your code to see what Python returns.