Sub topic 3
Counting non-null values with count
This chapter assumes you can build a pandas Series and DataFrame and select a column. You should also know that a missing value shows up as NaN or None. The chapter covers what count returns, how it differs from len, size and value_counts, and which values it treats as missing.
What count does
count returns the number of entries that are not missing. A value is missing if pandas recognizes it as null: NaN, None, pd.NA, or NaT for datetimes. Everything else counts, including empty strings, zeros, and False.
The examples in this chapter use one small DataFrame. One city is missing.
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Rome", "Oslo", "Paris", "Rome", "Oslo", None],
"plan": ["free", "pro", "free", "pro", "pro", "pro", "free"],
})
print(df["city"].count()) # 6, the missing value is skipped
print(len(df["city"])) # 7, length includes the missing value
print(df["city"].size) # 7, size is also the total number of entriescount is the only one of these three that looks at the contents. len and size only report how many slots exist.
Series.count versus DataFrame.count
On a Series, count returns one integer. On a DataFrame, it returns a Series with one count per column.
print(df.count())
# city 6
# plan 7
# dtype: int64
print(df.count(axis=1).tolist())
# [2, 2, 2, 2, 2, 2, 1]With the default axis=0, count works down each column. With axis=1, it works across each row and tells you how many fields are filled in. The last row has only its plan value, so its count is 1.
This makes count a quick completeness check. Compare it with the row count to see how much of each column is filled.
completeness = df.count() / len(df)
print(completeness.round(3))
# city 0.857
# plan 1.000
# dtype: float64The complement: counting missing values
To count missing values, use isna and add up the True values. Each True counts as 1.
missing_per_column = df.isna().sum()
print(missing_per_column)
# city 1
# plan 0
# dtype: int64The two views always agree: count() + isna().sum() equals len(df) for each column. The relationship is useful for checking your work.
assert (df.count() + df.isna().sum() == len(df)).all()A related shortcut is df.notna().mean(). It gives the same fractions as df.count() / len(df), because the mean of a Boolean column is the share of True values.
What counts as missing
count only trusts pandas' own null markers. It cannot know that your data uses a placeholder.
import numpy as np
s = pd.Series(["Oslo", "", "N/A", None, "Rome"])
print(s.count()) # 4: only None is missing; "" and "N/A" are ordinary stringsIf a placeholder should be treated as missing, convert it first.
cleaned = s.mask(s.isin(["", "N/A"])) # replaces matching entries with NaN
print(cleaned.count()) # 2: only "Oslo" and "Rome" remainOther cases to know about:
| Value | Counted by `count`? |
|---|---|
| `np.nan`, `None`, `pd.NA`, `pd.NaT` | No |
| `""` (empty string) | Yes |
| `0` and `False` | Yes |
| `"NaN"` or `"N/A"` as text | Yes |
| `np.inf` and `-np.inf` | Yes |
Infinity is a frequent surprise. A column containing np.inf reports it as a valid value. Convert it with replace([np.inf, -np.inf], np.nan) if it should be missing.
Missing values can also hide behind data types. A column read from a CSV with text placeholders is an object column of strings. Fixing this usually means passing na_values=[...] to read_csv, so the placeholders become real nulls at load time.
Choosing between len, count, size and nunique
Several tools look similar but answer different questions.
| Expression | Question it answers | Missing values |
|---|---|---|
| `len(s)` or `s.size` | How many entries are there? | Included |
| `s.count()` | How many entries have a value? | Excluded |
| `s.nunique()` | How many different values are there? | Excluded by default |
| `s.value_counts().sum()` | How many entries have a value, summed from the frequency table? | Excluded by default |
The last row shows a useful identity. value_counts() drops missing values by default, so its counts add up to count(), not to len().
print(df["city"].value_counts().sum()) # 6, equals count()
print(df["city"].count()) # 6Adding dropna=False to value_counts makes the sum equal len() instead.
Counting within groups
After groupby, count runs once per group. This is where it differs most from size.
rows_per_plan = df.groupby("plan").size()
print(rows_per_plan)
# plan
# free 3
# pro 4
# dtype: int64
cities_per_plan = df.groupby("plan")["city"].count()
print(cities_per_plan)
# plan
# free 2
# pro 4
# Name: city, dtype: int64The free group has three rows, but one has no city, so size says 3 and count of city says 2. A later chapter covers this comparison in depth. For now, remember the rule: size counts rows, and count counts non-missing values in a chosen column.
Calling count on the whole grouped D# Counting non-null values with count
count answers a narrow question: how many entries in this column hold a real value? This chapter covers what count returns for a Series, a DataFrame, and each row. It also covers how it differs from len and size, and which values it fails to treat as missing. It assumes you can build a DataFrame, select a column, and that you know pandas marks absent data as NaN or None.
The example data
The chapter uses one DataFrame throughout. The last row has no city.
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Rome", "Oslo", "Paris", "Rome", "Oslo", None],
"plan": ["free", "pro", "free", "pro", "pro", "pro", "free"],
})What count returns
Series.count() returns the number of non-missing entries as an integer. DataFrame.count() does the same for each column and returns a Series indexed by column name.
print(df["city"].count()) # 6
print(df.count())
# city 6
# plan 7
# dtype: int64The DataFrame has 7 rows. city reports 6 because one entry is missing, and plan reports 7 because none are.
count, len, and size
Three tools look similar but answer different questions.
| Expression | Counts | Result for `df["city"]` |
|---|---|---|
| `len(df["city"])` | All rows, missing or not | 7 |
| `df["city"].size` | All elements, missing or not | 7 |
| `df["city"].count()` | Non-missing entries only | 6 |
On a Series, len and size always agree. The difference between count and the other two is exactly the number of missing values.
total = len(df["city"]) # 7
non_null = df["city"].count() # 6
missing = total - non_null # 1The same relationship gives you a missing-value report.
Equivalent expressions with isna and notna
count is shorthand for summing a Boolean mask of non-missing entries. The two forms give the same number.
print(df["city"].notna().sum()) # 6, same as count()
print(df["city"].isna().sum()) # 1, the number of missing values
print(df["city"].isna().mean()) # 0.14285714285714285, the fraction missingUse count when you want the non-missing total. Use isna().sum() or isna().mean() when the missing values are the thing you are reporting. For a whole-DataFrame summary, df.isna().sum() gives the missing count per column and df.isna().mean() gives the fraction per column.
Counting across a row
Pass axis=1 to count non-missing values in each row instead of each column.
print(df.count(axis=1))
# 0 2
# 1 2
# 2 2
# 3 2
# 4 2
# 5 2
# 6 1
# dtype: int64Row 6 has only one filled field. This is useful for finding sparse rows. For example, df[df.count(axis=1) < 2] selects rows with fewer than two filled fields.
What counts as missing
count treats these as missing: NaN, None, pd.NA, and NaT (a missing timestamp). Both None in an object column and NaN in a numeric column are excluded.
Several values look empty but are not missing, and count includes them:
- An empty string
"". - A string of spaces such as
" ". - Placeholder text such as
"N/A","unknown", or"-". - Sentinel numbers such as
-1or999. float("inf")and-inf.
This is the most common source of wrong counts. Data loaded from files often has blanks that never became NaN.
s = pd.Series(["Oslo", "", " ", None, "Rome"])
print(s.count()) # 4, only None is missing
cleaned = s.mask(s.str.strip() == "") # blank strings become NaN
print(cleaned.count()) # 2s.str.strip() returns NaN for the None entry. Comparing that to "" gives False, so mask leaves it as missing. For other placeholders, convert them to NaN first. One option is s.replace("N/A", pd.NA). Another is the na_values argument of pd.read_csv. Then call count.
How count relates to value_counts
By default, value_counts drops missing values, so its counts add up to count. This is a quick consistency check.
freq = df["city"].value_counts()
print(freq.sum()) # 6
print(freq.sum() == df["city"].count()) # TrueIf you pass dropna=False to value_counts, the sum becomes 7 and matches len instead. When the sum of a frequency table disagrees with the number you expected, check which of these two numbers you were comparing against.
Counting within groups
count works on grouped data too. Here it counts non-missing values of the selected column in each group.
print(df.groupby("plan")["city"].count())
# plan
# free 2
# pro 4
# Name: city, dtype: int64
print(df.groupby("plan").size())
# plan
# free 3
# pro 4
# dtype: int64The free group has three rows, but one has no city. count gives 2 and size gives 3. Use size to count rows per group. Use count to count filled values of a particular column per group. A later chapter returns to this choice in detail.
Calling count on the whole grouped DataFrame, as in df.groupby("plan").count(), returns a table with one non-missing count per remaining column.
Choosing the right tool
The diagram shows how to pick between the options in this chapter.
Common errors
- Using
countwhen you meant the number of rows.df["city"].count()is 6 here, not 7. Uselen(df)for rows. - Expecting
countto give distinct values. It counts entries, not different entries. Usenuniquefor that, covered in a later chapter. - Trusting
counton unclean text. Blank strings and placeholders pass as real values, as shown above. - Calling
counton a DataFrame and reading it as one number. It returns one number per column. To get a single total of filled cells, usedf.count().sum(), which is 13 here. - Confusing
countwithvalue_counts.countreturns a single integer.value_countsreturns a frequency table.
Summary of behavior
countreturns the number of non-missing entries, per column for a DataFrame and per row withaxis=1.lenandsizeinclude missing entries.countdoes not.countequalsnotna().sum().- Empty strings, placeholders, and sentinel numbers are not missing until you convert them.
- In a groupby,
countskips missing values in the chosen column andsizedoes not.
Exercise
A Series is built as pd.Series([4.0, None, 7.5, float("nan"), 0.0, float("inf")]). What do len, count(), and isna().sum() return, and why?
Show answer
len returns 6, because it counts every entry. count() returns 4: the entries 4.0, 7.5, 0.0, and inf are all non-missing, because pandas treats inf as a real value, while None (stored as NaN in a float Series) and float("nan") are missing. isna().sum() returns 2, the two missing entries. This agrees with 6 - 4 = 2.
Exercise
A column status holds the values "active", "", "n/a", None, and "active". status.count() returns 4, but only two entries hold real data. How would you get the correct count?
Show answer
Convert the blank and placeholder values to missing first, then count. For example: status.replace({"": pd.NA, "n/a": pd.NA}).count() returns 2. count on the original returns 4 because only None is recognized as missing.