how to get the ratio of missing values in pandas df column in python

To get the ratio of missing values in a Pandas DataFrame column in Python, you can use the following code:

main.py
import pandas as pd

# create sample dataframe
df = pd.DataFrame({'A': [1, 2, None, 4, None],
                   'B': [None, 6, 7, None, 9],
                   'C': ['a', 'b', None, 'd', 'e']})

# calculate ratio of missing values in each column
missing_value_ratios = df.isna().mean()

# print the missing_value_ratios
print(missing_value_ratios)
348 chars
13 lines

Output:

main.py
A    0.4
B    0.4
C    0.2
dtype: float64
42 chars
5 lines

The output shows that column A and B have 40% missing values and column C has 20% missing values.

related categories

gistlibby LogSnag