Remove Rows with Infinite Values from pandas DataFrame in Python (Example Code)

This article demonstrates how to drop infinite values from a pandas DataFrame in Python.

Setting up the Example

import pandas as pd                                        # Import pandas library in Python
import numpy as np                                         # Load NumPy library
my_df = pd.DataFrame({'A':[5, np.inf, 5, 1, 2, 8, 2],      # Construct example DataFrame in Python
                      'B':[np.inf, 1, 2, 3, 4, 5, 6]})
print(my_df)                                               # Display example DataFrame in console
#      A    B
# 0  5.0  inf
# 1  inf  1.0
# 2  5.0  2.0
# 3  1.0  3.0
# 4  2.0  4.0
# 5  8.0  5.0
# 6  2.0  6.0

Example: Replace inf by NaN & Drop Rows with NaN

my_df.replace([np.inf, - np.inf], np.nan, inplace = True)  # Replace inf
print(my_df)                                               # Display updated data
#      A    B
# 0  5.0  NaN
# 1  NaN  1.0
# 2  5.0  2.0
# 3  1.0  3.0
# 4  2.0  4.0
# 5  8.0  5.0
# 6  2.0  6.0
my_df = my_df.dropna()                                     # Drop rows with NaN
print(my_df)                                               # Display updated data
#      A    B
# 2  5.0  2.0
# 3  1.0  3.0
# 4  2.0  4.0
# 5  8.0  5.0
# 6  2.0  6.0

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