
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check If a Value is Infinity or NaN in Python
One of the most important aspects of any programming language is the ability to handle numbers, including values that may be infinite or undefined. In Python, the concepts of infinity and NaN (Not a Number) are important to understand, as they are often encountered in mathematical calculations and data analysis. In this tutorial, we will explore how to check for infinity and NaN values in Python.
Infinity in Python
Infinity is a mathematical concept that represents a number that is larger than any finite number. In Python, infinity is represented by the keyword "inf". This keyword is used to represent values that are too large to be stored in the computer's memory, such as the result of dividing a number by zero or computing the square root of a negative number.
To check whether a value is infinity in Python, you can use the math module. This module provides a function called "isinf" that returns True if the given value is infinity and False otherwise.
Example
Here are the examples
import math x = float('inf') print(math.isinf(x)) # True
Output
After implementing the above lines of code, you will get the following output
True
Example
Take a look at the following example
import math x = float('10') print(math.isinf(x)) # False
Output
After implementing the above lines of code, you will get the following output
False
In the above examples, we first define a variable "x" that is set to the infinity value using the float() function. We then use the "isinf" function from the math module to check if "x" is infinity. Since in first example, "x" is indeed infinity, the function returns True. Whereas in second example, "x" is not infinity, the function returns False.
Example
You can also check if a value is negative infinity by using the same "isinf" function and passing a negative infinity value
import math x = float('-inf') print(math.isinf(x)) # True
Output
After implementing the above lines of code, you will get the following output
True
In this example, we define a variable "x" that is set to negative infinity using the float() function and then pass it to the "isinf" function. Since "x" is negative infinity, the function returns True.
NaN in Python
NaN (Not a Number) is another mathematical concept that represents an undefined or unrepresentable value. In Python, NaN is represented by the keyword "nan". This keyword is used to represent values that are the result of an undefined operation, such as taking the square root of a negative number or performing a division by zero.
To check whether a value is NaN in Python, you can use the math module again. This module provides a function called "isnan" that returns True if the given value is NaN and False otherwise. Here are the examples
Example
import math x = float('nan') print(math.isnan(x)) # True
Output
After implementing the above lines of code, you will get the following output
True
Example
Now, take a look at the following example
import math x = float('10') print(math.isnan(x)) # False
Output
After implementing the above lines of code, you will get the following output
False
In these examples, we first define a variable "x" that is set to the NaN value using the float() function. We then use the "isnan" function from the math module to check if "x" is NaN. Since in first example, "x" is indeed NaN, the function returns True. Whereas in the second example, "x" is not NaN, the function returns False.
Example
It is important to note that NaN values are not equal to any other value, including other NaN values. Therefore, you cannot use the "==" operator to compare NaN values. Instead, you should use the math.isnan function to check for NaN values.
import math x = float('nan') y = float('nan') print(x == y) # False print(math.isnan(x)) # True print(math.isnan(y)) # True
Output
After implementing the above lines of code, you will get the following output
False True True
In this example, we define two variables "x" and "y" that are both set to the NaN value using the float() function. We then use the == operator to compare "x" and "y", which returns False since NaN values are not equal to any other value. Finally, we use the "isnan" function to check if both "x" and "y" are NaN, which returns True for both variables.
Checking for Infinity and NaN in NumPy
NumPy is a popular library in Python for numerical computations, and it also provides functions for checking for infinity and NaN values. The NumPy module provides two functions: "isinf" and "isnan". These functions behave similarly to the ones provided by the math module, but they can also handle arrays and matrices of values.
Example
Here is an example of how to use the "isinf" function from NumPy to check if an array contains any infinity values
import numpy as np x = np.array([1, 2, 3, np.inf]) print(np.isinf(x)) # [False False False True]
Output
After implementing the above lines of code, you will get the following output
[False False False True]
In this example, we define an array "x" that contains four values, including the infinity value. We then use the "isinf" function from NumPy to check which values in "x" are infinity. The function returns a boolean array with the same shape as "x", where True values indicate that the corresponding element in "x" is infinity.
Example
Here is an example of how to use the "isnan" function from NumPy to check if an array contains any NaN values
import numpy as np x = np.array([1, 2, np.nan, 4]) print(np.isnan(x)) # [False False True False]
Output
After implementing the above lines of code, you will get the following output
[False False True False]
In this example, we define an array "x" that contains four values, including the NaN value. We then use the "isnan" function from NumPy to check which values in "x" are NaN. The function returns a boolean array with the same shape as "x", where True values indicate that the corresponding element in "x" is NaN.
Checking for Infinity and NaN in Pandas
Pandas is a popular data manipulation library in Python that provides several functions for working with dataframes and series. Pandas also provides functions for checking for infinity and NaN values in dataframes and series.
Example
Here are some examples of how to check for infinity and NaN values in Pandas
import pandas as pd import numpy as np # Create a dataframe df = pd.DataFrame({ 'A': [1, 2, 3, np.inf], 'B': [4, 5, 6, np.nan], 'C': [7, 8, np.nan, 9] }) # Check for infinity values inf_mask = df.isin([np.inf, -np.inf]) print(inf_mask) # Check for NaN values nan_mask = df.isna() print(nan_mask)
Output
After implementing the above lines of code, you will get the following output
A B C 0 False False False 1 False False False 2 False False False 3 True False False A B C 0 False False False 1 False False False 2 False False True 3 False True False
In this example, we create a dataframe "df" that contains several columns with different types of values, including infinity and NaN values. We then use the "isin" function to check for infinity values and the "isna" function to check for NaN values.
The "isin" function returns a boolean dataframe with the same shape as "df", where True values indicate that the corresponding element in "df" is infinity or negative infinity.
The "isna" function returns a boolean dataframe with the same shape as "df", where True values indicate that the corresponding element in "df" is NaN.
Handling Infinity and NaN Values
When dealing with infinity and NaN values in Python, it is important to consider how they will affect the computation or analysis being performed. In many cases, these values can cause unexpected results or errors, so it is important to handle them appropriately.
For example, if you are performing a mathematical calculation that involves division by a variable that may be zero, you should check for this condition and handle it appropriately. Here is an example
Example
x = 1 y = 0 if y == 0: result = float('inf') else: result = x / y
In this example, we define two variables "x" and "y" and perform a division operation between them. Since "y" may be zero, we check for this condition and handle it appropriately by setting the result to infinity if "y" is zero.
Similarly, if you are performing data analysis that involves NaN values, you should consider how these values will affect your results. For example, if you are computing the mean or standard deviation of a set of values that may contain NaN values, you should use functions that can handle these values appropriately.
Example
Here is an example of how to compute the mean of a set of values that may contain NaN values
import numpy as np x = np.array([1, 2, np.nan, 4]) mean = np.nanmean(x) print(mean)
Output
After implementing the above lines of code, you will get the following output
2.3333333333333335
In this example, we define an array "x" that contains four values, including the NaN value. We then use the "nanmean" function from NumPy to compute the mean of the values in "x", excluding any NaN values. The function returns the mean value as a float.
Conclusion
Understanding how to check for infinity and NaN values in Python is an important skill for any developer or data analyst working with numerical data. These values can occur in a variety of mathematical calculations and data analysis tasks, and it is important to handle them appropriately to avoid unexpected results or errors.
By using the built-in functions and modules provided by Python, developers and data analysts can effectively handle these values and ensure the accuracy of their calculations and analyses.