Drop Rows with NaN in pandas DataFrame Column in Python (2 Examples)

In this article, I’ll show how to drop rows containing NaN values in a pandas DataFrame in Python.

Preparing the Examples

import pandas as pd                                              # Import pandas in Python
my_df = pd.DataFrame({"col1":[9, 8, float("NaN"), float("NaN"), 7, 6, 5],  # Example DataFrame
                     "col2":[float("NaN"), 1, 1, float("NaN"), 1, 1, 1],
                     "col3":[float("NaN"), 10, float("NaN"), 11, float("NaN"), 12, 13],
                     "col4":["A", "B", float("NaN"), "C", float("NaN"), "D", "E"]})
print(my_df)                                                     # Displaying example DataFrame
#    col1  col2  col3 col4
# 0   9.0   NaN   NaN    A
# 1   8.0   1.0  10.0    B
# 2   NaN   1.0   NaN  NaN
# 3   NaN   NaN  11.0    C
# 4   7.0   1.0   NaN  NaN
# 5   6.0   1.0  12.0    D
# 6   5.0   1.0  13.0    E

Example 1: Delete All NaN Values in pandas DataFrame

my_df_1 = my_df.dropna()                                         # Using dropna()
print(my_df_1)                                                   # Displaying new data
#    col1  col2  col3 col4
# 1   8.0   1.0  10.0    B
# 5   6.0   1.0  12.0    D
# 6   5.0   1.0  13.0    E

Example 2: Delete NaN Values in Particular Column of pandas DataFrame

my_df_2 = my_df.dropna(subset = ["col4"])                        # Using dropna() & subset
print(my_df_2)                                                   # Displaying new data
#    col1  col2  col3 col4
# 0   9.0   NaN   NaN    A
# 1   8.0   1.0  10.0    B
# 3   NaN   NaN  11.0    C
# 5   6.0   1.0  12.0    D
# 6   5.0   1.0  13.0    E

Leave a Reply

Your email address will not be published.

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