Lesson

Missing Values and Checks Before Computing in pandas

A check of a real table before any calculation, on 1,035 rows of planets outside the Solar System and 398 car models: counting the gaps with isna, a share from a 0/1 column, removing rows with dropna and subset, filling with fillna and what it changes, copy before a change, numbers stored as text, and five lines of code before an analysis.

Last updated:


In this lesson we learn to check a table before we compute from it:
missing values with isna, a share from a 0/1 column, dropna and fillna, a change made in a copy, and numbers stored as text with pd.to_numeric.

The typical mass of a planet

Suppose we write a one-page summary of the planets found outside the Solar System until 2014, and it opens with the typical mass of such a planet.
The data are the table exoplanets.csv of New columns and groups in pandas.
One line answers at once:

The examples run in your browser: select Run from top to bottom, because the boxes of this page share their variables with each other.
The first run of the page loads pandas, so it can take a moment.

import pandas as pd

planets = pd.read_csv('exoplanets.csv')
print(planets.shape)
print(round(planets['mass'].mean(), 2))
(1035, 6)
2.64

The summary could now say “the mean mass is 2.64 Jupiter masses”.
The sentence goes wrong, and nothing in the output says so: the table has missing values, and the number was computed without looking at them.

Predict. mean() returned a number, although some planets have no mass in the table.
Of how many of the 1,035 rows is 2.64 the mean?

Show a hint

Recall what mean() of a column does with NaN, from Tables in pandas.

Show the answer

mean() skips NaN, so 2.64 is the mean of the rows that have a mass:
513 of the 1,035, as the count of gaps in the section below shows.
Which 513 they are is the question of the section a rate from a 0/1 column.

Counting the gaps of every column

The method isna(), which Merging tables and repeated rows in pandas used on one column, works on a whole table too:
it returns a table of the same shape with True where a value is missing.
sum() of a table sums each column, and True counts as 1, so it counts the gaps of each column; mean() gives their share of the rows:

missing = planets.isna()
print(missing.sum())
print(missing.mean().round(3))
method              0
number              0
orbital_period     43
mass              522
distance          227
year                0
dtype: int64
method            0.000
number            0.000
orbital_period    0.042
mass              0.504
distance          0.219
year              0.000
dtype: float64

Practice

Your turn. Print the number of rows whose distance is missing, and after a space their share of all the rows, rounded to three digits after the decimal point.

# your code here
Show a hint

isna() works on one column too, and returns a mask.

Show a solution
no_distance = planets['distance'].isna()
print(no_distance.sum(), round(no_distance.mean(), 3))
227 0.219
Show a common mistake and why it happens
distance = planets['distance']
print(distance.count(), round(distance.count() / len(planets), 3))

The method count() counts the values that are present, so 808 and 0.781 are the rows that have a distance and their share, not the ones without.

A rate from a 0/1 column

A mean of the 513 known masses describes all the planets only if the planets with a mass are like the others.
A 0/1 column holds 1 when a row has a property and 0 when it does not.
The method notna() returns True where a value is not missing, and astype(int), from NumPy arrays, turns True into 1 and False into 0.
The sum of a 0/1 column is the number of its 1s, so its mean is their share:

planets['mass_known'] = planets['mass'].notna().astype(int)
k = planets['mass_known']
print(k.sum(), round(k.mean(), 3))
known = planets.groupby('method')['mass_known'].mean()
print(known.loc[['Radial Velocity', 'Transit']].round(3))
513 0.496
method
Radial Velocity    0.922
Transit            0.003
Name: mass_known, dtype: float64

The mass is known in 513 of the 1,035 rows, a share of 0.496, and the share differs by method.

Practice

Your turn. For each method, print the share of its rows whose distance from the Sun is known, rounded to three digits after the decimal point, as a Series.

# your code here
Show a hint

Build a 0/1 column for the distance as the box above did for the mass.

Show a solution
planets['distance_known'] = (
    planets['distance'].notna().astype(int)
)
by_d = planets.groupby('method')['distance_known']
print(by_d.mean().round(3))
method
Astrometry                       1.000
Eclipse Timing Variations        0.444
Imaging                          0.842
Microlensing                     0.435
Orbital Brightness Modulation    0.667
Pulsar Timing                    0.200
Pulsation Timing Variations      0.000
Radial Velocity                  0.958
Transit                          0.564
Transit Timing Variations        0.750
Name: distance_known, dtype: float64
Show a common mistake and why it happens
planets['distance_known'] = (
    planets['distance'].notna().astype(int)
)
by_d = planets.groupby('method')['distance_known']
print(by_d.sum())

The sum of the 0/1 column is the number of rows with a known distance in each method, not their share.
A larger group has more of them even when its share is smaller.

The answer about the mean mass

The 2.64 Jupiter masses of the opening are the mean of 513 rows.
The share 0.922 of the 553 rows of radial velocity is 510 rows, and the share 0.003 of the 397 rows of transit is 1 row:
in this table the masses come almost only from radial velocity, while 396 of the 522 rows without a mass are of transit planets.
The missing values are not spread at random over the planets, and the 513 known masses are not a typical sample of the 1,035 rows.
For a planet found by radial velocity the measured value is usually a minimum mass (written M sin i), because the tilt of its orbit is not known, so even the known masses are mostly lower limits.

None of the four repeated rows of Merging tables and repeated rows in pandas has a mass, so the 513 rows with a mass are 513 planets.
The summary can write: “the mean mass of the 513 planets with a known mass, 510 of them found by radial velocity, is 2.64 Jupiter masses”.
Why a method has no mass the table does not say (the file description says only that a method may not measure a quantity), and the masses of the other 522 rows it cannot tell.

Removing rows with gaps: dropna

The method dropna() returns a new table without the rows that have a missing value in any column.
With the argument subset, a list of columns, it removes only the rows with a gap in those columns.
The method median() returns the median, the value of 50% in describe().

Predict. Does planets.dropna() keep more rows than 513, the number of rows with a mass, or fewer?

complete = planets.dropna()
print(len(complete), len(planets.dropna(subset=['mass'])))
period = 'orbital_period'
print(planets[period].median(), complete[period].median())
498 513
39.9795 357.0

dropna() keeps 498 rows: it also removes the 15 rows that have a mass but miss a distance or an orbital period.
The removal also changed a question that does not use the mass:
the median orbital period of the 992 rows that have one is 40 days, and of the 498 complete rows 357 days, because the rows without a mass went too.
The columns in subset are the ones the question uses.

Practice

Your turn. Print the number of rows that have both an orbital period and a distance.

# your code here
Show a hint

The argument subset takes a list of the columns that must have a value.

Show a solution
both = planets.dropna(subset=['orbital_period', 'distance'])
print(len(both))
776
Show a common mistake and why it happens
print(len(planets.dropna()))

Without subset the method removes a row with a gap in any column, so the 498 rows are the rows that also have a mass.

The six cars without horsepower

To compare removing with filling on a few rows we take auto-mpg.csv, the 398 car models of NumPy arrays and Tables in pandas (Auto MPG, UCI Machine Learning Repository, Quinlan, 1993, CC BY 4.0), where the horsepower of 6 models is missing:

cars = pd.read_csv('auto-mpg.csv')
no_hp = cars['horsepower'].isna()
cols = ['name', 'model_year', 'cylinders', 'horsepower']
print(cars[no_hp][cols])
                     name  model_year  cylinders  horsepower
32             ford pinto          71          4         NaN
126         ford maverick          74          6         NaN
330  renault lecar deluxe          80          4         NaN
336    ford mustang cobra          80          4         NaN
354           renault 18i          81          4         NaN
374        amc concord dl          82          4         NaN

Filling gaps: fillna

The method fillna(value) returns a new column, or table, in which every NaN is replaced by value:
it fills the missing values. The value can be a constant, such as 0, or a statistic of the column, such as its mean.
The method std() returns the standard deviation, the std of describe().

Predict. Which of the two filled columns below keeps the mean of 104.47 horsepower?

hp = cars['horsepower']
zero = hp.fillna(0)
by_mean = hp.fillna(hp.mean())
print(round(hp.mean(), 2), round(zero.mean(), 2),
      round(by_mean.mean(), 2))
print(round(hp.std(), 2), round(zero.std(), 2),
      round(by_mean.std(), 2))
104.47 102.89 104.47
38.49 40.27 38.2

What filling changes

Filling with 0 gives six cars an engine of no power and pulls the mean down.
Filling with the mean keeps the mean, because the added values equal it, and makes the spread smaller:
six values are exactly equal to the mean. Each filled value is also a claim about one car:
the 1971 Ford Pinto gets 104.5 horsepower, while the other Ford Pintos of the table have 72 to 97.
On the planets, half of the masses would be filled:

mass = planets['mass']
filled_mass = mass.fillna(mass.mean())
print(round(mass.std(), 2), round(filled_mass.std(), 2))
print(mass.median(), round(filled_mass.median(), 2))
3.82 2.69
1.26 2.64

The spread falls from 3.82 to 2.69 and the median moves to the mean itself.
A filled value is a value that the source did not give: we fill only when the question allows it, for example when a later step needs a value in every row, and we report how many values were filled and keep a mark of which.

Practice

Your turn. Fill the missing horsepower values of cars with the median horsepower, and print the mean horsepower of the filled column, rounded to two digits after the decimal point.

# your code here
Show a hint

median() of the column returns the value to fill with.

Show a solution
hp = cars['horsepower']
by_median = hp.fillna(hp.median())
print(round(by_median.mean(), 2))
104.3
Show a common mistake and why it happens
hp = cars['horsepower']
hp.fillna(hp.median())
print(round(hp.mean(), 2))

fillna returns a new column and does not change hp; the result was not kept in a variable, so 104.47 is the mean of the 392 values that were there before.

A change goes to a copy

To keep the filled values and a mark of which were filled, we change a copy of the table, while the table that read_csv returned stays as it was read.
An assignment b = a does not make a new table: it gives the same table a second name, so a column added through one name appears under the other.
The method copy() makes a table with values of its own, as for an array in NumPy arrays.

same = cars
filled = cars.copy()
filled['hp_filled'] = filled['horsepower'].isna()
hp_mean = filled['horsepower'].mean()
filled['horsepower'] = filled['horsepower'].fillna(hp_mean)
print(cars.shape, same.shape, filled.shape)
print(filled['hp_filled'].sum(), filled['horsepower'].isna().sum())
(398, 9) (398, 9) (398, 10)
6 0

cars, and same with it, still have 9 columns; the change went to the new variable filled, which has no gaps and a column hp_filled that marks the six rows whose value was not in the source.

Practice

Your turn. Make a table marked from cars, with a new column heavy that is True for the cars that weigh more than 4000 pounds, without changing cars.
Print the number of columns of cars and, after a space, of marked.

# your code here
Show a hint

The number of columns is the second value of shape.

Show a solution
marked = cars.copy()
marked['heavy'] = marked['weight'] > 4000
print(cars.shape[1], marked.shape[1])
9 10
Show a common mistake and why it happens
marked = cars
marked['heavy'] = marked['weight'] > 4000
print(cars.shape[1], marked.shape[1])

marked = cars gives the same table a second name, so the new column was added to cars too and both have 10 columns.

Numbers stored as text

A file can hold numbers as text, for example when an empty cell is written ?; read_csv then reads the whole column as text, so its sorting and its largest value compare text, character by character.
The function pd.to_numeric turns a column into numbers; it stops with a ValueError at a value that is not a number, unless errors='coerce' tells it to write NaN there.
The small table below is written by us: the horsepower of the first three rows of auto-mpg.csv and of the 1971 Ford Pinto as text, with ? for the missing value.
The table is built from a dictionary with pd.DataFrame, as in Merging tables and repeated rows in pandas.

text_hp = pd.DataFrame({
    'name': ['chevrolet chevelle malibu', 'buick skylark 320',
             'plymouth satellite', 'ford pinto'],
    'horsepower': ['130', '165', '150', '?'],
})
hp_numbers = pd.to_numeric(text_hp['horsepower'], errors='coerce')
print(text_hp['horsepower'].max(), hp_numbers.max())
print(hp_numbers.isna().sum())
? 165.0
1

As text, the largest value is ?, which comes after the digits, and no error warns us.
After the conversion, the gaps are the values that were not numbers.

Predict. A column written by us holds the texts '7.10', 'n/a', '2,60' and '19.4'.
How many of them does pd.to_numeric with errors='coerce' turn into NaN?
(In the answer, pd.Series(list) builds the column from a list.)

Show the answer
masses = pd.Series(['7.10', 'n/a', '2,60', '19.4'])
print(pd.to_numeric(masses, errors='coerce').isna().sum())
2

n/a is not a number, and neither is 2,60, written with a decimal comma.

Five lines of code before an analysis

A value can be present and still be wrong: a negative distance, a year outside the period of the data.
The rows min and max of describe() show the range of each column of numbers, here on the table as read from the file:

df = pd.read_csv('exoplanets.csv')
print(df.describe().loc[['min', 'max']])
     number  orbital_period     mass  distance    year
min     1.0        0.090706   0.0036      1.35  1989.0
max     7.0   730000.000000  25.0000   8500.00  2014.0

No value is negative, and the years are 1989 to 2014, as the file description says.
The longest orbital period, 730,000 days, met in New columns and groups in pandas, is far from the others:
such a value is checked against the source, because the table alone cannot say whether it is right.

These five lines of code run on any table read with read_csv, named df as above, before the first calculation:

print(df.shape)
df.info(memory_usage=False)
print(df.isna().sum())
print(df.describe().loc[['min', 'max']])
print(df.duplicated().sum())

They answer: how many rows and columns; the type of each column, where a column of numbers read as text shows str (object before pandas 3.0); how many values each column lacks; whether a value is outside its possible range; and how many rows repeat, with duplicated() of Merging tables and repeated rows in pandas.
Each answer goes into the report next to the result: “of 1,035 rows, 513 with a mass”, not “the planets”.

Keep in mind

  • df.isna().sum() counts the missing values of each column, and isna().mean() gives their share. A mean of the values that are present describes the rows that have them.
  • The mean of a 0/1 column is a share; by group, it shows where the values are present.
  • dropna(subset=[...]) removes the rows with a gap in the columns the question uses; dropna() removes a gap in any column.
  • fillna invents values: filling with the mean keeps the mean and shrinks the spread. Mark the filled rows.
  • b = a is a second name for the same table; a change goes to a copy made with copy().
  • pd.to_numeric(column, errors='coerce') turns text into numbers; the new gaps are the values that were not numbers.
  • Before the first calculation, five lines check a table: shape, info(), isna().sum(), the rows min and max of describe() for a value outside its possible range, and duplicated().sum().