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
Types, dates & missingness · W16 · 8 MIN

Drop missing rows

Exclude only rows missing a required field.

Exercises within this concept

  1. FollowFollow the techniqueCurrent exercise
  2. ChangeAdapt a requirement
  3. TransferChoose and combine

Understand the idea

dropna removes rows missing required fields. Use subset to restrict the check to fields the report actually needs.

Concept sketch: drop rows missing the required valuerowpriceA2BNaNC4rowpriceA2C4drop rows missing the required value
Illustration · not the exercise output

A small example

A row with price=8 and discount=missing survives subset=["price"], but fails subset=["price", "discount"].

Follow the code

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

df["price"] = pd.to_numeric(df["price"], errors="coerce")
df = df.dropna(subset=["price"])
df

What each part does

dropna(subset=["price"])
require a known price
subset=
consider only these columns

Your inputs

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

Messy café orders · 8 synthetic rows
orderdrinksizepricetipdate
101" latte "LARGE6.2012026-06-01
102TEAsmall3.100.52026-06-02
103" mocha "LARGEoopsNonenot a date
104LatteSmallNone0.82026-06-04
104LatteSmallNone0.82026-06-04
105"tea "SMALL4.200.62026-06-05
106ESPRESSOsmall2.500.22026-06-06
107" mocha"large6.801.52026-06-07

Your task · Follow

  1. Using df, convert price to numeric, then keep only rows with a known numeric price.
  2. Do not require a known tip or date.
  3. Keep the changes in df and display it.
  4. Use: to_numeric(), dropna().
Hint

subset names the fields required by this report; unrelated missing fields must not remove a row.

Reveal solution

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

df["price"] = pd.to_numeric(df["price"], errors="coerce")
df = df.dropna(subset=["price"])
df
Your task · Follow
  1. Using df, convert price to numeric, then keep only rows with a known numeric price.
  2. Do not require a known tip or date.
  3. Keep the changes in df and display it.
  4. Use: to_numeric(), dropna().

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.