Module 3 · pandas · Lesson 18 of 66

Missing data

Find, drop and fill the gaps in a data set.

In this lesson · about 10 minutes

  • Spot missing values with isnull
  • Drop rows or columns with dropna
  • Fill gaps with fillna, such as the column mean

Real data has holes. pandas marks a missing value as NaN. You have two main choices: drop what's missing, or fill it in.

CodeWhat it does
df.isnull()True wherever a value is missing
df.dropna()Drop every row with any missing value
df.dropna(axis=1)Drop every column with any missing value
df.dropna(thresh=2)Keep rows that have at least 2 real values
df.fillna(value=0)Replace missing values
df['A'].fillna(value=df['A'].mean())Fill a column's gaps with its average

Exercise

Count the gaps

Get the number of missing values in each column of df.

Code that runs before yours
import numpy as np
import pandas as pd
df = pd.DataFrame({'A': [1, 2, np.nan, 4], 'B': [5, np.nan, np.nan, 8], 'C': [1, 2, 3, np.nan]})

Exercise

Fill with the average

Fill the missing values in column B with the mean of column B, and save it back into df['B'].

Code that runs before yours
import numpy as np
import pandas as pd
df = pd.DataFrame({'A': [1, 2, np.nan, 4], 'B': [5, np.nan, np.nan, 8], 'C': [1, 2, 3, np.nan]})

Exercise

Keep mostly complete rows

Keep only the rows of df that have at least 3 real (non-missing) values.

Code that runs before yours
import numpy as np
import pandas as pd
df = pd.DataFrame({'A': [1, 2, np.nan, 4], 'B': [5, np.nan, np.nan, 8], 'C': [1, 2, 3, np.nan]})

Exercises solved: 0 of 3

Tip: solve each exercise first. Press Check to test your code.

Noviq Academy's Data Science course is free and for learning. Python runs in your browser with Pyodide, which downloads about 20 MB the first time, plus a few more for scikit-learn. Your code and progress stay on this device. The salaries data is a sample of San Francisco's public pay records; the purchases, customers, housing, advertising and classified data are made up. The Titanic, tips, flights and iris data sets come from Seaborn's examples; the maps use public 2011 to 2014 US and world figures. The 911 data is a 20,000-call sample of Montgomery County, Pennsylvania's public 911 records; the movie ratings are the MovieLens 100K data from GroupLens Research; the reviews are a 3,000-review sample from the Yelp Dataset Challenge; the loans are public LendingClub data; the colleges are the College data from An Introduction to Statistical Learning; the bank notes, kyphosis and breast cancer data come from the UCI Machine Learning Repository. Spark and TensorFlow can't run in a browser, so those lessons use stand-ins that run here, and show the code for the real tools.