How to Count the Number of Empty Columns in a Python DataFrame?

Estimated read time 2 min read

To count the number of empty columns (i.e., columns with no values) in a Python DataFrame, you can use the isnull() method to create a DataFrame of Boolean values indicating where each cell in the original DataFrame is empty, and then use the sum() method to count the number of empty cells in each column. Finally, you can filter the resulting Series to only include columns with no empty cells and count the length of the filtered Series to get the number of empty columns.

Here’s an example:

import pandas as pd

# create a sample DataFrame
df = pd.DataFrame({'col1': [1, 2, None, 4], 'col2': [None, None, None, None], 'col3': ['a', 'b', 'c', 'd']})

# count the number of empty cells in each column
empty_cols = df.isnull().sum()

# filter the resulting Series to only include columns with no empty cells
empty_cols = empty_cols[empty_cols == len(df)]

# count the length of the filtered Series to get the number of empty columns
num_empty_cols = len(empty_cols)

print(f'The DataFrame has {num_empty_cols} empty columns.')

In this example, we create a sample DataFrame with three columns (col1, col2, and col3) and four rows. We then use the isnull() method to create a DataFrame of Boolean values indicating where each cell in the original DataFrame is empty. We apply the sum() method to count the number of empty cells in each column, resulting in a Series with the column names as indices and the number of empty cells as values.

We then filter the resulting Series to only include columns with no empty cells by selecting only the values where the number of empty cells is equal to the length of the DataFrame. Finally, we count the length of the filtered Series to get the number of empty columns and print the result to the console.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply