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.
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.
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)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.
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()))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.
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())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.
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)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
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.
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())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]
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)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.
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
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)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?
isna() gives True for missing cells, and summing True values counts them per column.
2. The values are 4, NaN and 8. What is their mean()?
pandas skips NaN, so the mean is (4 + 8) / 2 = 6.0.
3. What does df.dropna(subset=["price"]) do?
subset limits the check to the listed columns; rows missing a price are removed.