Check if dataframe contains infinity in Python – Pandas
There are various cases where a data frame can contain infinity as value. This article discusses how we can keep track of infinities in our data frame.
- Import module
- Create a data frame, for this article, it is done using a dictionary. For including infinity in the data, import NumPy module, and use np.inf for positive infinity and -np.inf for negative infinity.
- Use appropriate methods from the ones mentioned below as per your requirement.
Method 1: Use DataFrame.isinf() function to check whether the dataframe contains infinity or not. It returns boolean value. If it contains any infinity, it will return True. Else, it will return False.
isinf(array [, out])
Using this method itself, we can derive a lot more information regarding the presence of infinity in our dataframe:
- Checking for infinity as values
- Counting the number of infinity values
- Retrieve column name with infinity as value(s)
- Retrieve row index/indices with infinity as value(s)
Method 2: Use np.isfinite(dataframe_name) to check the presence of infinite value(s). It returns boolean value. It will return False for infinite values and it will return True for finite values.
isfinite(array [, out])