How to Count NaN in pandas DataFrame in Python (2 Examples)

In this tutorial you’ll learn how to count the number of NaN values in a pandas DataFrame in Python.

Preparing the Examples

import pandas as pd                                     # Import pandas library in Python
my_df = pd.DataFrame({'A':[1, 1, 1, float('NaN'), 1],  # Construct example DataFrame
                      'B':[2, float('NaN'), 2, float('NaN'), 2],
                      'C':[float('NaN'), float('NaN'), 3, 3, float('NaN')]})
print(my_df)                                           # Display example DataFrame in console
#      A    B    C
# 0  1.0  2.0  NaN
# 1  1.0  NaN  NaN
# 2  1.0  2.0  3.0
# 3  NaN  NaN  3.0
# 4  1.0  2.0  NaN

Example 1: Number of NaN Values by Column

print(my_df.isna().sum())                              # Count NaNs
# A    1
# B    2
# C    3
# dtype: int64

Example 2: Number of NaN Values by Row

print(my_df.isnull().sum(axis = 1))                    # Count NaNs
# 0    1
# 1    2
# 2    0
# 3    2
# 4    1
# dtype: int64

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top