ADVERTISEMENT
ADVERTISEMENT

How to count the NaN values in a single column in pandas DataFrame?

Given a DataFrame, we have to count the NaN values in a single column.
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 deal with this type of data, you can either remove the particular row (if the number of missing values is low) or you can handle these values. For handling these values, you might need to count the number of NaN values.

To count the number of NaN values, you can use the sum() method over the isnull() method, below is the syntax:

data.isnull().sum()

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.

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

# Importing Numpy package
import numpy as np

# Creating a dictionary
dict = {
    "Months": [
        "January",
        np.NaN,
        "March",
        "April",
        np.nan,
        "June",
        np.nan,
        "July",
        "August",
        np.nan,
        "October",
        "November",
        np.NaN,
    ]
}

# Creating the dataframe
df = pd.DataFrame(dict)

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

# Applying the isnull method
nan = df["Months"].isnull().sum()

# printing the number of NaN values present
print("Number of NaN values present: ", nan)

Output:

count the NaN values in a single column

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.