Sub topic 5
Finding missing values with non-null counts
This chapter assumes you can run Python, have pandas imported as pd, and know that a DataFrame is a table of rows and labelled columns. Earlier chapters covered head, tail, shape, and the basic layout of info. Here you use the non-null counts in that output to find missing data, and you learn where those counts can mislead you.
What a non-null count tells you
A missing value in pandas is an entry that holds NaN (not a number), None, NaT (missing datetime), or pd.NA. A non-null count is the number of entries in a column that are not any of these.
If a DataFrame has 5 rows and a column has 4 non-null values, one value is missing. The comparison is simple:
- Missing values = total rows minus non-null count.
- A column whose non-null count equals the row count is complete, at least as far as pandas can tell.
The qualifier matters, and a later section returns to it. pandas only recognises its own missing-value markers. It cannot know that "unknown" or -999 in your data means "missing".
Reading the counts in `info`
Start with the DataFrame from the earlier chapters. The age column contains one np.nan.
import numpy as np
import pandas as pd
df = pd.DataFrame({
"name": ["Ana", "Ben", "Cleo", "Dev", "Eli"],
"age": [34, 28, np.nan, 45, 39],
"city": ["Lima", "Oslo", "Lima", "Pune", "Oslo"],
"salary": [52000, 48000, 61000, 75000, 58000],
})
df.info()The output looks like this. The memory figure varies between machines and versions.
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 5 entries, 0 to 4
Data columns (total 4 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 name 5 non-null object
1 age 4 non-null float64
2 city 5 non-null object
3 salary 5 non-null int64
dtypes: float64(1), int64(1), object(2)
memory usage: 292.0+ bytesCompare two numbers:
- The line
RangeIndex: 5 entries, 0 to 4gives the total row count, 5. - The
Non-Null Countcolumn gives each column's count of real values.
name, city, and salary show 5, so they are complete. age shows 4, so one value is missing.
The age dtype is float64 even though every age looks like a whole number. NaN is a floating-point value, and an integer NumPy column cannot hold it. pandas therefore converts the whole column to float. A numeric column that you expected to be int64 but shows as float64 is often a sign of missing values.
Getting the same numbers as data
info prints text and returns None. You cannot sort it, filter it, or store it. When you need the counts as data, use these methods:
print(df.count())
print(df.isna().sum())
print(len(df) - df.count())The output for each line:
name 5
age 4
city 5
salary 5
dtype: int64
name 0
age 1
city 0
salary 0
dtype: int64
name 0
age 1
city 0
salary 0
dtype: int64df.count()returns the non-null count per column, the same figures asinfo.df.isna().sum()builds a table ofTrueandFalseflags, then sums each column.Truecounts as 1, so the sum is the number of missing values.len(df) - df.count()gives the same result by subtraction.
You can combine these into a small report. Percentages help when comparing columns in tables of different sizes.
import numpy as np
import pandas as pd
df = pd.DataFrame({
"name": ["Ana", "Ben", "Cleo", "Dev", "Eli"],
"age": [34, 28, np.nan, 45, 39],
"city": ["Lima", "Oslo", "Lima", "Pune", "Oslo"],
"salary": [52000, 48000, 61000, 75000, 58000],
})
report = pd.DataFrame({
"non_null": df.count(),
"missing": df.isna().sum(),
"missing_pct": (df.isna().mean() * 100).round(1),
})
print(report.sort_values("missing", ascending=False)) non_null missing missing_pct
age 4 1 20.0
name 5 0 0.0
city 5 0 0.0
salary 5 0 0.0df.isna().mean() works because the mean of a column of True and False flags is the fraction of True values.
Once you know which column has gaps, find the rows:
print(df[df.isna().any(axis=1)]) name age city salary
2 Cleo NaN Lima 61000isna().any(axis=1) is True for each row that has at least one missing value. Using that as a filter returns only those rows.
Which tool to use
| Tool | Returns | Best for |
|---|---|---|
| `df.info()` | Printed text, `None` | A fast visual check next to dtypes |
| `df.count()` | Series of non-null counts | Using counts in code |
| `df.isna().sum()` | Series of missing counts | Reporting how much is missing |
| `df.isna().mean()` | Series of fractions | Comparing columns by share missing |
| `df.describe()` `count` row | Non-null counts, numeric columns only by default | Seeing how many values each statistic used |
The `count` row in `describe`
describe skips missing values when it computes statistics. Its count row shows how many values each statistic used.
print(df["age"].describe())count 4.000000
mean 36.500000
std 7.505553
min 28.000000
25% 32.500000
50% 36.500000
75% 41.500000
max 45.000000
Name: age, dtype: float64The count is 4, not 5. The mean of 36.5 is the average of 34, 28, 45, and 39. Cleo's row is not treated as zero and is not part of the calculation. If a column's count is far below the row count, its mean and quartiles describe only a subset of your data.
When the counts are wrong
Non-null counts can mislead you in four cases.
Placeholders that pandas does not recognise
Many datasets mark missing data with a text or number code. pandas counts these as real values.
import numpy as np
import pandas as pd
raw = pd.DataFrame({
"id": [1, 2, 3, 4],
"email": ["[email protected]", "", "n/a", None],
"score": [10, -999, 8, np.nan],
})
raw.info()<class 'pandas.core.frame.DataFrame'>
RangeIndex: 4 entries, 0 to 3
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 id 4 non-null int64
1 email 3 non-null object
2 score 3 non-null float64
dtypes: float64(1), int64(1), object(1)
memory usage: 228.0+ bytesemail shows 3 non-null, but only one address is real. The empty string and "n/a" are ordinary text. score shows 3 non-null, but the value -999 is a code for "not recorded". Only None and np.nan were detected.
Placeholders usually show up in describe or value_counts. A minimum of -999 in a column of test scores is an obvious red flag.
Reading files: `na_values`
When you load a CSV file, read_csv already treats several strings as missing, including the empty string, NA, N/A, n/a, NaN, and null. The DataFrame constructor does not do this. For other codes, pass na_values.
import io
import pandas as pd
csv = "id,email,score\n1,[email protected],10\n2,,-999\n3,n/a,8\n4,,\n"
clean = pd.read_csv(io.StringIO(csv), na_values=["-999"])
clean.info()<class 'pandas.core.frame.DataFrame'>
RangeIndex: 4 entries, 0 to 3
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 id 4 non-null int64
1 email 1 non-null object
2 score 2 non-null float64
dtypes: float64(1), int64(1), object(1)
memory usage: 228.0+ bytesNow email shows 1 real value and score shows 2. The counts agree with what is actually in the data. If the data is already loaded, df.replace(-999, np.nan) does the same job.
Wide or large DataFrames
By default, info shows non-null counts only when the DataFrame is smaller than the options display.max_info_rows and display.max_info_columns. Past those limits, it prints a shorter summary without per-column counts. You can force the full output:
df.info(show_counts=True)For a table with more than 100 columns, verbose=True also lists every column. In that case df.isna().sum() is often easier to read than info, because you can sort it and filter it to the non-zero entries.
Missing values hidden by dtype
The Non-Null Count column is accurate for all dtypes, but the dtype affects how gaps look elsewhere:
- Integer columns with gaps become
float64, as seen withage. - pandas also has nullable types such as
Int64, with a capital I, which keep integers and store gaps aspd.NA. The non-null count treatspd.NAas missing in the same way. - An all-missing column has a count of 0. Its dtype is often
objectorfloat64, anddescribehas nothing to summarise for it.
A short habit
When you meet a new DataFrame, do these steps in order:
- Run
df.info()and compare each non-null count with the entries line. - Note every column with a lower count, and every numeric column with an unexpected
float64orobjectdtype. - Use
isna().sum()or thereporttable above to quantify the gaps. - Use
df[df.isna().any(axis=1)]to see a few affected rows. - Scan
describefor placeholder values such as-999,0, or empty strings that the counts cannot catch.
Deciding what to do about the gaps (filling, dropping, or going back to the source) is a cleaning task, and it comes after you understand them.
Exercise
A DataFrame orders has 200 rows. orders.info() shows quantity as float64 with 200 non-null, and orders["quantity"].describe() reports a minimum of -1. Which of these claims is justified: (a) no values are missing, (b) the column has no missing values that pandas can detect, but -1 may be a placeholder? What check would you run next, and how would you convert the placeholder?
Show answer
Claim (b) is justified. A count of 200 non-null means pandas found no NaN, None, NaT, or pd.NA, but it cannot recognise -1 as a code for "unknown". The float64 dtype is also odd for a quantity, which hints that the column once held gaps or was read in a way that produced floats. Next, run orders["quantity"].valuecounts().head() or (orders["quantity"] == -1).sum() to see how many rows carry -1. If it is a placeholder, convert it with orders["quantity"] = orders["quantity"].replace(-1, np.nan), or pass navalues=["-1"] when reading the file. Then run orders.info() again. The non-null count should drop by the number of replaced rows.
Exercise
Write one expression that returns, for a DataFrame df, the names of the columns that have at least one missing value.
Show answer
df.columns[df.isna().any()] returns an Index of those column names. df.isna().any() gives one True or False per column, and using it to select from df.columns keeps only the columns marked True. An equivalent version is df.columns[df.count() < len(df)].