Data analysis with pandas · Lesson 8 of 15

Missing data: isna, fillna, dropna

Find empty cells in a table, count them, fill them with a value or an average, or drop the rows, and see how sums and means treat NaN.

About 14 minutes · code runs in your browser, nothing to install

Real tables have holes: a sensor that did not report, a form field left empty. pandas marks a missing number as NaN ("not a number"). Python's None in a list turns into NaN in a number column, and an empty cell in a CSV file does too.

Pythoneditable
import pandas as pd

df = pd.DataFrame({
    "city": ["Rome", "Oslo", "Nice", "Bern", "Cork"],
    "mon": [14.0, None, 16.0, 9.0, 11.0],
    "tue": [15.0, 3.0, None, None, 12.0],
})
print(df)
Output
   city   mon   tue
0  Rome  14.0  15.0
1  Oslo   NaN   3.0
2  Nice  16.0   NaN
3  Bern   9.0   NaN
4  Cork  11.0  12.0

NaN shows where a value is missing.

Finding the holes

isna() gives True for every missing cell. Add .sum() to count them per column, which is usually the first thing to check in a new file. notna() is the opposite.

Pythoneditable
import pandas as pd

df = pd.DataFrame({
    "city": ["Rome", "Oslo", "Nice", "Bern", "Cork"],
    "mon": [14.0, None, 16.0, 9.0, 11.0],
    "tue": [15.0, 3.0, None, None, 12.0],
})
print(df.isna().sum())
print(df[df["tue"].isna()]["city"].tolist())
print("Rows with no gaps:", int(df.notna().all(axis=1).sum()))
Output
city    0
mon     1
tue     2
dtype: int64
['Nice', 'Bern']
Rows with no gaps: 2

all(axis=1) asks, for each row, whether all its cells are True.

Sums and averages skip NaN

sum(), mean() and count() ignore missing values. That is usually what you want, but remember the average is then taken over fewer values.

Pythoneditable
import pandas as pd

tue = pd.Series([15.0, 3.0, None, None, 12.0])
print("Values:", tue.count(), "of", len(tue))
print("Sum:", tue.sum())
print("Mean:", tue.mean())
Output
Values: 3 of 5
Sum: 30.0
Mean: 10.0

Filling gaps

fillna(value) puts a value in every hole and returns a new DataFrame. A dictionary fills each column with its own value, and a column's mean is a common choice for numbers. Assign the result back to keep it.

Pythoneditable
import pandas as pd

df = pd.DataFrame({
    "city": ["Rome", "Oslo", "Nice", "Bern", "Cork"],
    "mon": [14.0, None, 16.0, 9.0, 11.0],
    "tue": [15.0, 3.0, None, None, 12.0],
})
print(df.fillna(0))
filled = df.fillna({"mon": df["mon"].mean(), "tue": 10.0})
print(filled)
Output
   city   mon   tue
0  Rome  14.0  15.0
1  Oslo   0.0   3.0
2  Nice  16.0   0.0
3  Bern   9.0   0.0
4  Cork  11.0  12.0
   city   mon   tue
0  Rome  14.0  15.0
1  Oslo  12.5   3.0
2  Nice  16.0  10.0
3  Bern   9.0  10.0
4  Cork  11.0  12.0
Watch out: Avoid df["tue"].fillna(0, inplace=True). It is a form of chained assignment and may not change df. Write df["tue"] = df["tue"].fillna(0) instead.

Dropping rows

dropna() removes every row with at least one missing value. subset= looks only at some columns, and ffill() copies the last known value down, which suits readings over time.

Pythoneditable
import pandas as pd

df = pd.DataFrame({
    "city": ["Rome", "Oslo", "Nice", "Bern", "Cork"],
    "mon": [14.0, None, 16.0, 9.0, 11.0],
    "tue": [15.0, 3.0, None, None, 12.0],
})
print(df.dropna())
print(len(df.dropna(subset=["mon"])), "rows have a Monday value")
print(df["tue"].ffill().tolist())
Output
   city   mon   tue
0  Rome  14.0  15.0
4  Cork  11.0  12.0
4 rows have a Monday value
[15.0, 3.0, 3.0, 3.0, 12.0]
Pythoneditable
import pandas as pd

people = pd.DataFrame({"name": ["Ana", "Ben", "Chloe"],
                       "email": ["ana@mail.test", None, "chloe@mail.test"]})
people["email"] = people["email"].fillna("unknown")
print(people)
Output
    name            email
0    Ana    ana@mail.test
1    Ben          unknown
2  Chloe  chloe@mail.test

Text columns have gaps too (shown as None or NaN); fillna works the same way.

✎ Exercise

Count the missing prices, then fill them with the average price rounded to 2 decimals and print the table.

Hint: isna().sum() counts; df["price"].mean() ignores the gaps; assign the fillna result back to the column.

Your codewrite your answer, then Run
import pandas as pd

df = pd.DataFrame({"item": ["tea", "cake", "milk", "jam"],
                   "price": [2.5, None, 1.2, None]})
# your code here

Expected output:

Missing: 2
   item  price
0   tea   2.50
1  cake   1.85
2  milk   1.20
3   jam   1.85
Show a solution
Solutioneditable
import pandas as pd

df = pd.DataFrame({"item": ["tea", "cake", "milk", "jam"],
                   "price": [2.5, None, 1.2, None]})
print("Missing:", int(df["price"].isna().sum()))
avg = round(float(df["price"].mean()), 2)
df["price"] = df["price"].fillna(avg)
print(df)
Output
Missing: 2
   item  price
0   tea   2.50
1  cake   1.85
2  milk   1.20
3   jam   1.85

Check yourself

1. What does df.isna().sum() show?

2. The values are 4, NaN and 8. What is their mean()?

3. What does df.dropna(subset=["price"]) do?

Spotted a mistake on this page? Tell us