How to Count the Total Number of Null and ISNA Values in Python?

Estimated read time 2 min read

In Python, you can count the total number of null or NaN (Not a Number) values in a DataFrame or Series using the isna() method in combination with the sum() method. Here’s an example:

import pandas as pd

# Create a sample DataFrame
df = pd.DataFrame({'A': [1, 2, None, 4, None],
                   'B': [None, 2, 3, None, 5],
                   'C': [1, 2, 3, 4, 5]})

# Count the total number of null or NaN values in the DataFrame
null_count = df.isna().sum().sum()

print("Total number of null or NaN values: ", null_count)

In this example, we first create a sample DataFrame using the pd.DataFrame() function from the pandas library. The DataFrame has three columns ‘A’, ‘B’, and ‘C’, and contains some null or NaN values.

We then use the isna() method on the DataFrame df to create a boolean mask where True indicates the presence of a null or NaN value, and False indicates the absence of a null or NaN value. The isna() method returns a DataFrame of the same shape as df with boolean values.

Next, we use the sum() method twice to count the number of True values in the boolean mask, once for each axis. The first sum() method sums the values along the rows (axis=0), and the second sum() method sums the values along the columns (axis=1). Finally, we use sum() again to get the total count of null or NaN values across all columns in the DataFrame. The result is stored in the null_count variable and printed.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply