Open In App

Count the NaN values in one or more columns in Pandas DataFrame

Last Updated : 17 Aug, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

Let us see how to count the total number of NaN values in one or more columns in a Pandas DataFrame. In order to count the NaN values in the DataFrame, we are required to assign a dictionary to the DataFrame and that dictionary should contain numpy.nan values which is a NaN(null) value.

Consider the following DataFrame.




# importing the modules
import numpy as np
import pandas as pd
   
# creating the DataFrame
dictionary = {'Names': ['Simon', 'Josh', 'Amen'
                        'Habby', 'Jonathan', 'Nick', 'Jake'],
              'Capitals': ['VIENNA', np.nan, 'BRASILIA'
                           np.nan, 'PARIS', 'DELHI', 'BERLIN'],
              'Countries': ['AUSTRIA', 'BELGIUM', 'BRAZIL'
                            np.nan, np.nan, 'INDIA', np.nan]}
table = pd.DataFrame(dictionary, columns = ['Names'
                                           'Capitals'
                                           'Countries'])
  
# displaying the DataFrame
display(table)


Output :

Example 1 : Counting the NaN values in a single column.




print("Number of null values in column 1 : " + 
       str(table.iloc[:, 1].isnull().sum()))
print("Number of null values in column 2 : " + 
       str(table.iloc[:, 2].isnull().sum()))


Output :

Number of null values in column 1 : 2
Number of null values in column 2 : 3

Example 2 : Counting the NaN values in a single row.




print("Number of null values in row 0 : " + 
       str(table.iloc[0, ].isnull().sum()))
print("Number of null values in row 1 : " + 
       str(table.iloc[1, ].isnull().sum()))
print("Number of null values in row 3 : " + 
       str(table.iloc[3, ].isnull().sum()))


Output :

Number of null values in row 0 : 0
Number of null values in row 1 : 1
Number of null values in row 3 : 2

Example 3 : Counting the total NaN values in the DataFrame.




print("Total Number of null values in the DataFrame : " + 
       str(table.isnull().sum().sum()))


Output :

Total Number of null values in the DataFrame : 5

Example 4 : Counting the NaN values in all the columns.




display(table.isnull().sum())


Output :



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads