How to delete NaN rows in Pandas

In this article, you’ll learn how to delete NaN rows in Pandas. The two examples given that will help you to delete NaN rows with different options.

Example 1: Delete NaN rows of Pandas DataFrame

This code will delete NaN rows if there is any NaN value present in a row. In this example, it will delete the 2nd row that has a single NaN value.

# Import the required libaries
import pandas as pd
import numpy as np

# Create a DataFrame
df = pd.DataFrame({'col_1': [21, np.nan, 53, 64],
                    'col_2': [55, 66, 87, 98],
                    'col_3': [19, 50, 71, 82]})

# Display the DataFrame
print(df)

# Delete the NaN Rows
df = df.dropna(axis = 0, how = 'any')

# Display the DataFrame after delete the NaN rows
print(df)

Output:

   col_1  col_2  col_3
0   21.0     55     19
1    NaN     66     50
2   53.0     87     71
3   64.0     98     82
   col_1  col_2  col_3
0   21.0     55     19
2   53.0     87     71
3   64.0     98     82

Example 2:

This code will delete the NaN row only if all the values are NaN. In this example, it will delete only the 2nd row but not delete the 4th row.

# Import the required libaries
import pandas as pd
import numpy as np


# Create a DataFrame
df = pd.DataFrame({'col_1': [21, np.nan, 53, np.nan],
                    'col_2': [55, np.nan, 87, 98],
                    'col_3': [19, np.nan, 71, 82]})

# Display the DataFrame
print(df)

# Delete the NaN Rows
df = df.dropna(axis = 0, how = 'all')

# Display the DataFrame after delete the NaN rows
print(df)

Output:

   col_1  col_2  col_3
0   21.0   55.0   19.0
1    NaN    NaN    NaN
2   53.0   87.0   71.0
3    NaN   98.0   82.0
   col_1  col_2  col_3
0   21.0   55.0   19.0
2   53.0   87.0   71.0
3    NaN   98.0   82.0

If you want to learn Pandas, I recommend this book and free resource.

Leave a Comment

Your email address will not be published.