Lesson 11 of 23
โฎPrev Nextโฏ

PY-401 ยท Cleaning messy data

Missing values

โฑ 9 min ๐Ÿ Real Python 3 ๐ŸŽฌ Animated

11of 23

Your note

My notes for this lesson

Select any text in the lesson to highlight it or add a note. Saved in this browser.

    No highlights yet. Select a sentence in the lesson, then pick a colour or add a note.

    All my bookmarks and notes

    Reading settings

    For every lesson, saved in this browser.

    Text size
    Line spacing
    Font

    With IaaS you rent the virtual machine. Microsoft looks after the building, power and hardware; you patch the operating system.

    โšก The 30-second answer

    Missing values are empty cells, which pandas shows as NaN (or None for text). df.isna().sum() counts them per column, df.dropna() removes rows that have any, and df["col"].fillna(value) fills them in. Decide per column: drop the row, fill with a sensible value such as the mean, or mark it as "Unknown".

    • Count missing values per column
    • Drop rows with dropna
    • Fill gaps with fillna

    Try it

    Watch it come alive, run it yourself, then prove it. Real Python, right on this page.

    Watch Python run the example. Every variable is a jar; watch the values change and the output appear.

    Missing values, running
    1. import numpy as np
    2. import pandas as pd
    3. sales = pd.DataFrame({
    4. "store": ["Pune", "Leeds", "Oslo", "Lyon"],
    5. "units": [12, np.nan, 9, 15],
    6. "manager": ["Asha", "Ben", None, "Dina"],
    7. })
    8. print(sales.isna().sum())
    9. print(sales.dropna())
    10. sales["units"] = sales["units"].fillna(sales["units"].mean())
    11. sales["manager"] = sales["manager"].fillna("Unknown")
    12. print(sales)
    Press โ–ถ to watch Python run this, one line at a time.
    1. The problemA store export has 4 rows, but Leeds forgot to send its units and nobody filled in Oslo's manager. Average the units now and the empty cell quietly changes the answer.
    2. The Python ideadf.isna().sum()Missing values are empty cells, which pandas shows as NaN (or None for text).
    3. In real lifeA hospital dashboard fills missing heart-rate readings with the patient's previous reading (ffill()) instead of the ward average, because a gap of one minute means "probably unchanged".

    Start with a question

    A store export has 4 rows, but Leeds forgot to send its units and nobody filled in Oslo's manager. Average the units now and the empty cell quietly changes the answer.

    Real data always has gaps. Ignoring them gives wrong totals and averages, and many machine-learning tools refuse to run with NaN in the data.

    Explain it like I'm 10

    Missing values are blank boxes on a worksheet. Before you add up the answers, you either cross out the rows with blanks or write your best guess in each blank.

    The technical explanation

    NaN means "not a number" and marks a missing value. In text columns pandas may show None. isna() finds both.

    df.isna().sum() is the first thing to run on a new file: one count per column.

    df.dropna() drops every row with any gap. df.dropna(subset=["units"]) only looks at the columns you name.

    fillna fills gaps: a fixed value such as 0 or "Unknown", or a statistic such as df["units"].mean(). Assign the result back to the column.

    Syntax

    df.isna().sum()
    df.dropna(subset=["col"])
    df["col"] = df["col"].fillna(value)

    โ–ถ Run the example ๐ŸŽฌ Watch it come alive

    Real-world scenario

    A hospital dashboard fills missing heart-rate readings with the patient's previous reading (ffill()) instead of the ward average, because a gap of one minute means "probably unchanged".

    Ready for more?The full lesson adds the technical explanation, interview questions and quick revision.

    Test yourself

    5 questions. Get 4 right and this lesson is marked complete.

    1. 1. How do you count missing values in each column?
    2. 2. What does df.dropna() do with no arguments?
    3. 3. How do you only drop rows missing "price"?
    4. 4. What does NaN stand for?
    5. 5. df["units"].fillna(df["units"].mean()) fills gaps withโ€ฆ

    Questions people ask

    Should I drop or fill missing values in pandas?

    Drop rows when only a few are missing and they are not special. Fill when dropping would lose too much data: use 0 or "Unknown" when that is the true meaning, the mean or median for numbers, or the previous value for readings over time.

    What is the difference between NaN and None in pandas?

    NaN is a floating-point marker for a missing number; None is Python's empty value and often appears in text columns. pandas treats both as missing, so isna, dropna and fillna handle them the same way.

    Interview questions

    How this topic comes up in Python interviews. Answer out loud first, then open the model answer.

    beginner Should I drop or fill missing values in pandas?

    Drop rows when only a few are missing and they are not special. Fill when dropping would lose too much data: use 0 or "Unknown" when that is the true meaning, the mean or median for numbers, or the previous value for readings over time.

    beginner What is the difference between NaN and None in pandas?

    NaN is a floating-point marker for a missing number; None is Python's empty value and often appears in text columns. pandas treats both as missing, so isna, dropna and fillna handle them the same way.

    intermediate How do you count missing values in each column?

    df.isna().sum(). isna marks gaps as True, and sum counts the Trues per column.

    intermediate What does df.dropna() do with no arguments?

    Drops every row that has any missing value. Any gap in a row removes that row.

    Quick revision

    Remember

    • Count missing values per column
    • Drop rows with dropna
    • Fill gaps with fillna
    • dropna() with no arguments drops a row if any column is empty, which can throw away most of your data. Use subset=["units"] to drop only rows missing the columns you need.

    Syntax

    df.isna().sum()
    df.dropna(subset=["col"])
    df["col"] = df["col"].fillna(value)

    Official documentation