ADVERTISEMENT
ADVERTISEMENT

How to check if any value is NaN in a Pandas DataFrame?

Given a DataFrame, we have to check if any value is NaN in it.
Submitted by Pranit Sharma, on April 24, 2022

While creating a DataFrame or importing a CSV file, there could be some NaN values in the cells. NaN values mean "Not a Number" which generally means that there are some missing values in the cell. To perform effective analysis of data, we need to learn how to deal with the Nan values?

In Pandas, we can find, if any value Nan values in our DataFrame. Read: Count NaN values in a single column. Here, we will learn how to count NaN values in the entire DataFrame?

pandas.isnull(obj) Method

The isnull() method returns a True or False value. Where, True means that there is some missing data and False means that the data is not null. True and False are treated as 1 and 0 respectively.

pandas.isnull().sum().sum() Method

The sum() method returns the count of True values generated from the isnull() method.

Here, you have to use the sum() method twice to count the NaN values in the entire dataset. First, it will count the NaN values in each column and the second time it will add all the NaN values from all the columns.

To work with MultiIndex in Python Pandas, we need to import the pandas library. Below is the syntax,

import pandas as pd

Let us understand with the help of an example.

# Importing pandas package
import pandas as pd

# To create NaN values, you must import numpy package, 
# then you will use numpy.NaN to create NaN values
import NumPy as np

# Creating a dictionary with some NaN values
d = {
    "Name":['Payal','Mukti','Neelam','Shailendra'],
    "Age":[20,30,np.NaN,26],
    "Gender":['Male',np.NaN,np.NaN,'Female'],
    "Profession":['Doctor','Teacher','Singer',np.NaN]
}

# Now, Create DataFrame
df=pd.DataFrame(d)

# Printing the original DataFrame
print("Original DataFrame:\n")
print(df,"\n\n")

# Counting NaN values
NAN=df.isnull().sum().sum()

# Now, Printing the Number of NaN values
print("Total NaN values:")
print(NAN)

Output:

check if any value is NaN in a Pandas DataFrame

Python Pandas Programs »



ADVERTISEMENT


ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.