Remove infinite values from a given Pandas DataFrame

Remove infinite values from a given Pandas DataFrame

If you have a Pandas DataFrame with infinite values (both positive and negative) and you want to remove or replace them, you can use the functions np.inf and np.isinf from NumPy.

Here's a step-by-step guide:

1. Import necessary libraries:

import pandas as pd import numpy as np 

2. Create a sample DataFrame:

data = {'A': [1, 2, np.inf], 'B': [4, np.inf, 6], 'C': [-np.inf, 8, 9]} df = pd.DataFrame(data) print(df) 

This will output:

 A B C 0 1.0 4.0 -inf 1 2.0 inf 8.0 2 inf 6.0 9.0 

3. Remove infinite values:

a. Replace infinite values with NaN:

df.replace([np.inf, -np.inf], np.nan, inplace=True) print(df) 

This will replace infinite values with NaN:

 A B C 0 1.0 4.0 NaN 1 2.0 NaN 8.0 2 NaN 6.0 9.0 

b. Drop rows with NaN values (which were previously infinite values):

df.dropna(inplace=True) print(df) 

This will remove rows with NaN values:

 A B C 0 1.0 4.0 8.0 

4. Alternative approach: Replace infinite values with a specific value:

If you'd rather replace the infinite values with a specific value instead of removing them, you can do so in step 3a:

# Replace infinite values with a specific value, e.g., 9999 df.replace([np.inf, -np.inf], 9999, inplace=True) print(df) 

This will replace infinite values with 9999.

Choose the approach that best fits your needs, whether it's removing rows with infinite values or replacing them with a specific value.


More Tags

linear-algebra xamarin.forms.listview custom-font ionic3 arm http-proxy android-widget controls inline-images angular-components

More Programming Guides

Other Guides

More Programming Examples