TExcelTAD
Home › pandas › Cleaning Empty Cells

Cleaning Empty Cells

Empty cells are the most common data problem. pandas represents them as NaN (from NumPy, "not a number"); for dates the marker is NaT ("not a time"), and None in a text column is treated the same way. You have two basic choices: remove the rows that contain them, or fill them with a replacement value.

Finding empty cells

python · try it yourself
import numpy as np
import pandas as pd

readings = pd.DataFrame({
    "station": ["N1", "N2", "N3", "N4", "N5"],
    "temp": [21.4, np.nan, 19.8, 22.1, np.nan],
    "humidity": [55, 61, np.nan, 48, 52],
})
print(readings)
print(readings.isna())
print(readings.isna().sum())
  station  temp  humidity
0      N1  21.4      55.0
1      N2   NaN      61.0
2      N3  19.8       NaN
3      N4  22.1      48.0
4      N5   NaN      52.0
   station   temp  humidity
0    False  False     False
1    False   True     False
2    False  False      True
3    False  False     False
4    False   True     False
station     0
temp        2
humidity    1
dtype: int64

isna() returns a same-shaped table of True/False; notna() is its opposite. Summing counts the True values per column.

Removing rows with dropna()

dropna() returns a new DataFrame without the rows that contain any empty cell:

python · try it yourself
import numpy as np
import pandas as pd

readings = pd.DataFrame({
    "station": ["N1", "N2", "N3", "N4", "N5"],
    "temp": [21.4, np.nan, 19.8, 22.1, np.nan],
    "humidity": [55, 61, np.nan, 48, 52],
})
print(readings.dropna())
print(readings.dropna(subset=["temp"]))
print(len(readings), "rows in the original")
  station  temp  humidity
0      N1  21.4      55.0
3      N4  22.1      48.0
  station  temp  humidity
0      N1  21.4      55.0
2      N3  19.8       NaN
3      N4  22.1      48.0
5 rows in the original
Option Effect
subset=["temp"] only look at these columns
how="all" drop a row only if every value is missing
thresh=2 keep rows with at least 2 non-missing values
axis=1 drop columns instead of rows

Notice the original still has 5 rows: dropna() gives you a new object. Write readings = readings.dropna() to keep the result.

Note: Dropping is simple but throws information away. If 30% of rows have one empty cell, dropping them loses 30% of all your other measurements too. Filling is often the better choice.

Filling with fillna()

fillna() replaces empty cells with a value. Passing a dictionary sets a different value per column:

python · try it yourself
import numpy as np
import pandas as pd

readings = pd.DataFrame({
    "station": ["N1", "N2", "N3", "N4", "N5"],
    "temp": [21.4, np.nan, 19.8, 22.1, np.nan],
    "humidity": [55, 61, np.nan, 48, 52],
})
print(readings.fillna(0))
print(readings.fillna({"temp": 20.0, "humidity": 50}))
  station  temp  humidity
0      N1  21.4      55.0
1      N2   0.0      61.0
2      N3  19.8       0.0
3      N4  22.1      48.0
4      N5   0.0      52.0
  station  temp  humidity
0      N1  21.4      55.0
1      N2  20.0      61.0
2      N3  19.8      50.0
3      N4  22.1      48.0
4      N5  20.0      52.0

Filling with 0 is rarely right for measurements: a temperature of 0 is a real (and misleading) value. A typical value from the column is usually better.

Filling with the mean, median or mode

Statistic Method Good for
mean df["col"].mean() numbers without extreme outliers
median df["col"].median() numbers with outliers (it ignores extremes)
mode df["col"].mode()[0] categories, the most frequent value
python · try it yourself
import numpy as np
import pandas as pd

readings = pd.DataFrame({
    "station": ["N1", "N2", "N3", "N4", "N5"],
    "temp": [21.4, np.nan, 19.8, 22.1, np.nan],
    "humidity": [55, 61, np.nan, 48, 52],
    "sky": ["sun", None, "cloud", "sun", "rain"],
})
temp_mean = readings["temp"].mean()
hum_median = readings["humidity"].median()
sky_mode = readings["sky"].mode()[0]
print(round(temp_mean, 2), hum_median, sky_mode)

clean = readings.fillna({"temp": round(temp_mean, 2),
                         "humidity": hum_median,
                         "sky": sky_mode})
print(clean)
21.1 53.5 sun
  station  temp  humidity    sky
0      N1  21.4      55.0    sun
1      N2  21.1      61.0    sun
2      N3  19.8      53.5  cloud
3      N4  22.1      48.0    sun
4      N5  21.1      52.0   rain

mode() returns a Series (there can be ties), so [0] takes the first value.

Filling ordered data: ffill, bfill and interpolate

For measurements taken in order (hourly readings, daily prices), neighbouring values are the best guess. ffill() copies the last known value forward, bfill() copies the next value backward, and interpolate() draws a straight line between neighbours:

python · try it yourself
import numpy as np
import pandas as pd

hourly = pd.Series([10.0, np.nan, np.nan, 16.0, np.nan, 15.0],
                   index=["06h", "07h", "08h", "09h", "10h", "11h"])
print(pd.DataFrame({
    "raw": hourly,
    "ffill": hourly.ffill(),
    "bfill": hourly.bfill(),
    "interpolate": hourly.interpolate(),
}))
      raw  ffill  bfill  interpolate
06h  10.0   10.0   10.0         10.0
07h   NaN   10.0   16.0         12.0
08h   NaN   10.0   16.0         14.0
09h  16.0   16.0   16.0         16.0
10h   NaN   16.0   15.0         15.5
11h  15.0   15.0   15.0         15.0

Between 10 and 16, interpolate() filled in 12 and 14, evenly spaced. That is often the most realistic choice for smooth physical quantities like temperature.

Test yourself

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

  1. The price column
  2. Rows where price is missing
  3. Rows where any column is missing
  4. Nothing; subset is ignored

A column of house prices has a few huge outliers. Which value is usually safest to fill gaps with?

  1. The mean
  2. The median
  3. Zero
  4. The maximum

What does pd.Series([2.0, None, 6.0]).interpolate() give for the middle value?

  1. 2.0
  2. 4.0
  3. 6.0
  4. NaN