Python

Pandas Count NaN

This Pandas article will discuss how you can determine the number of NaN values in a Pandas DataFrame.

Pandas isnull() function

The isnull() function in Pandas allows us to determine missing values in a dataset. For example, we can use this function to get the number of NaN elements in a Pandas DataFrame.

Consider the example DataFrame shown below:

1
2
3
4
5
# import pandas and numpy
import pandas as pd
import numpy as np
df = pd.DataFrame([[1,2,np.nan, 3, 4, np.nan, 5, np.nan]])
df

The above creates a simple DataFrame containing NaN values.

Pandas Count NaN in Column

To count the number of NaN values in a single column, we can do:

1
print(f"null: {df[2].isnull().sum()}")

In the above example, we use the isnull() and sum() functions to determine the number of elements in column number 2.

The code above should return:

1
null: 1

Pandas Count NaN in DataFrame

To get the number of NaN values in the entire DataFrame, we can do:

1
print(f"NaN: {df.isnull().sum().sum()}")

This returns the number of NaN values in the specified DataFrame.

1
NaN: 3

Pandas Count NaN in Row

To find the number of NaN values in a row, we can use the loc and sum functions as shown in the example below:

1
print(f"NaN in row(0): {df.loc[0].isnull().sum()}")

The above should return the number of NaN values in the row at index 0.

1
NaN in row(0): 3

Conclusion

Using this guide, you learned how to determine the number of NaN values in a DataFrame column, entire DataFrame, and in a single row.

Thanks for reading!!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list