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.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
- 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])