Remove Rows with Empty Cells from pandas DataFrame in Python (2 Examples)

In this article, I’ll explain how to delete rows with empty cells from a pandas DataFrame in the Python programming language.

Setting up the Examples

import pandas as pd                                          # Import pandas library to Python
my_df = pd.DataFrame({'A':[5, '',' ', 5, '   ', 5, 5],       # Construct example DataFrame in Python
                      'B':['w', 'x','y', 'z', '', 'x', 'y']})
print(my_df)                                                 # Display example DataFrame in console
#      A  B
# 0    5  w
# 1       x
# 2       y
# 3    5  z
# 4        
# 5    5  x
# 6    5  y

Example 1: Replacing Empty Cells by NaN in pandas DataFrame in Python

my_df = my_df.replace(r'^s*$', float('NaN'), regex = True)  # Exchanging blanks by NaN
print(my_df)                                                 # Displaying updated DataFrame
#      A    B
# 0  5.0    w
# 1  NaN    x
# 2  NaN    y
# 3  5.0    z
# 4  NaN  NaN
# 5  5.0    x
# 6  5.0    y

Example 2: Deleting Rows with NaN Values in pandas DataFrame

my_df.dropna(inplace = True)                                 # Dropping rows with NaN
print(my_df)                                                 # Displaying updated DataFrame
#      A  B
# 0  5.0  w
# 3  5.0  z
# 5  5.0  x
# 6  5.0  y

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top