Check if dataframe contains infinity in Python - Pandas

Check if dataframe contains infinity in Python - Pandas

To check if a DataFrame contains any infinite values, you can use the numpy function isinf together with Pandas methods. Here's a step-by-step guide:

  1. Using numpy.isinf function:

    The numpy.isinf function can be applied to a Pandas DataFrame to get a boolean DataFrame of the same shape, where each True indicates the presence of an infinite value (np.inf or -np.inf) in the corresponding location.

  2. Using any method:

    Once you have a boolean DataFrame from the previous step, you can use the any method twice: first to check columns, and then to aggregate results for the whole DataFrame.

Here's an example:

import pandas as pd import numpy as np # Sample DataFrame df = pd.DataFrame({ 'A': [1, 2, 3], 'B': [np.inf, 5, 6], 'C': [7, 8, 9] }) # Check if the DataFrame contains any infinite values has_infinite = np.isinf(df).any().any() print(has_infinite) # Output: True 

To find out which columns contain infinite values:

infinite_columns = df.columns[np.isinf(df).any()].tolist() print(infinite_columns) # Output: ['B'] 

Using this approach, you can efficiently determine if there are any infinite values in your DataFrame and identify where they are located.


More Tags

asp.net listview memory-address array-formulas sql-like angular2-forms static-members batch-processing ubuntu-16.04 asynchronous

More Programming Guides

Other Guides

More Programming Examples