How do I count the NaN values in a column in pandas DataFrame?
You can use the isna()
function to create a boolean mask of the NaN values in a column, and then use the sum()
function to count the number of True
values in the mask. Here's an example:
import pandas as pd
# Create a sample DataFrame
df = pd.DataFrame({'A': [1, 2, 3, 4, float('nan')],
'B': [float('nan'), float('nan'), 5, 6, 7]})
# Count the number of NaN values in column 'A'
nan_count_a = df['A'].isna().sum()
# Count the number of NaN values in column 'B'
nan_count_b = df['B'].isna().sum()
print(nan_count_a) #1
print(nan_count_b) #2
Watch a video course
Python - The Practical Guide
You can also use df.isna().sum()
to get the number of NaN values of all columns.