search
Search
Login
Math ML
Map of Data Science
Join our weekly DS/ML newsletter
menu
menu search toc more_vert
Robocat
Guest 0reps
Thanks for the thanks!
close
Comments
Log in or sign up
Cancel
Post
account_circle
Profile
exit_to_app
Sign out
help Ask a question
Share on Twitter
search
keyboard_voice
close
Searching Tips
Search for a recipe:
"Creating a table in MySQL"
Search for an API documentation: "@append"
Search for code: "!dataframe"
Apply a tag filter: "#python"
Useful Shortcuts
/ to open search panel
Esc to close search panel
to navigate between search results
d to clear all current filters
Enter to expand content preview
icon_star
Doc Search
icon_star
Code Search Beta
SORRY NOTHING FOUND!
mic
Start speaking...
Voice search is only supported in Safari and Chrome.
Navigate to
A
A
brightness_medium
share
arrow_backShare

Counting number of rows with missing values in Pandas DataFrame

Pandas
chevron_right
Cookbooks
chevron_right
DataFrame Cookbooks
chevron_right
Handling Missing Values
schedule Jul 1, 2022
Last updated
local_offer PythonPandas
Tags

At least one missing value

Consider the following DataFrame:

df = pd.DataFrame({"A":[np.nan,3,np.nan],"B":[4,5,6],"C":[np.nan,7,8]}, index=["a","b","c"])
df
A B C
a NaN 4 NaN
b 3.0 5 7.0
c NaN 6 8.0

Solution

To count the number of rows that contain at least one missing value:

df.isna().any(axis=1).sum()
2

Explanation

We first use isna() method to get a DataFrame of booleans where True indicates the presence of NaN:

df.isna()
A B C
a True False True
b False False False
c True False False

We then use any(axis=1), which returns a Series of booleans where True indicates a row with at least one True:

df.isna().any(axis=1)
a True
b False
c True
dtype: bool

In Pandas, True is internally represented as a 1, while False as a 0. Therefore, taking the sum of this Series will return the number of rows with at least one missing value:

df.isna().any(axis=1).sum()
2

With all missing values

Consider the following DataFrame:

df = pd.DataFrame({"A":[np.nan,np.nan],"B":[3,np.nan]}, index=["a","b"])
df
A B
a NaN 3.0
b NaN NaN

Solution

To get the number of rows with all missing values:

df.isna().all(axis=1).sum()
1

Explanation

Once again, we first use isna() to get a DataFrame of booleans where True indicates the presence of NaN:

df.isna()
A B
a True False
b True True

Next, we use all(axis=1) to get a Series of booleans where True indicates a row with all Trues:

df.isna().all(axis=1)
a False
b True
dtype: bool

In Pandas, True is internally represented as a 1, while False as a 0, so taking the summation tells us the number of rows with all missing column values:

df.isna().all(axis=1).sum()
1
mail
Join our newsletter for updates on new DS/ML comprehensive guides (spam-free)
robocat
Published by Isshin Inada
Edited by 0 others
Did you find this page useful?
thumb_up
thumb_down
thumb_up
2
thumb_down
0
chat_bubble_outline
0
settings
Enjoy our search
Hit / to insta-search docs and recipes!