How do you check if a value is infinity in python?

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    In this article, we will check whether the given value is NaN or Infinity. This can be done using the math module. Let’s see how to check each value in detail.

    Check if the value is NaN

    NaN Stands for “Not a Number” and it is a numeric datatype used as a proxy for values that are either mathematically undefined or cannot be represented.  There are various examples of them like-

    1. 0/0 is undefined and NaN is used for representing it.
    2. Sqrt(-ve number) cannot be stored as a real number so NaN is used for representing it.
    3. Log(-ve number) cannot be stored as a real number so NaN is used for representing it.
    4. Inverse sin or Inverse cos of a number < -1 or number > 1 is also NaN.
    5. 0 * inf also leads to NaN.

    Since NaN is type in itself It is used to assign variables whose values are not yet calculated.

    Method 1: To check for NaN we can use math.isnan() function as NaN cannot be tested using == operator.  

    Python3

    import math

    x = math.nan

    print(f"x contains {x}")

    if(math.isnan(x)):

        print("x == nan")

    else:

        print("x != nan")

    Output

    x contains nan
    x == nan

    Method 2: NaN is not equal to NaN and therefore we can exploit this property to check for NaN. The following code demonstrates it.

    Python3

    import math

    def isNan(number):

        return number != number

    x = math.nan

    print(isNan(x))

    Check if the Value is Infinite

    Method 1: To check for infinite in python the function used is math.isinf() which only checks for infinite. To distinguish between positive and negative infinite we can add more logic that checks if the number is greater than 0 or less than 0. The code shows this in action.

    Python3

    import math

    def check(x):

        if(math.isinf(x) and x > 0):

            print("x is Positive inf")

        elif(math.isinf(x) and x < 0):

            print("x is negative inf")

        else:

            print("x is not inf")

    number = math.inf

    check(number)

    number = -math.inf

    check(number)

    Output

    x is Positive inf
    x is negative inf

    Method 2: Numpy also exposes two APIs to check for positive and negative infinite. which are np.isneginf()and np.isposinf()

    Python3

    import numpy as np

    print(np.isneginf([np.inf, 0, -np.inf]))

    print(np.isposinf([np.inf, 0, -np.inf]))

    Output

    [False False  True]
    [ True False False]

    View Discussion

    Improve Article

    Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    Prerequisites: 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. 

    Approach

    • 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. 

    Syntax:

    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)

    Example:

    Python3

    import pandas as pd

    import numpy as np

    data = {'Student ID': [10, 11, 12, 13, 14], 

            'Age': [23, 22, 24, 22, 25],

            'Weight': [66, 72, np.inf, 68, -np.inf]}

    df = pd.DataFrame(data)

    display(df)

    print()

    print("checking for infinity")

    ds = df.isin([np.inf, -np.inf])

    print(ds)

    print()

    print("printing the count of infinity values")

    count = np.isinf(df).values.sum()

    print("It contains " + str(count) + " infinite values")

    c = np.isinf(df['Weight']).values.sum()

    print("It contains " + str(c) + " infinite values")

    print()

    print("printing column name where infinity is present")

    col_name = df.columns.to_series()[np.isinf(df).any()]

    print(col_name)

    print()

    print("printing row index with infinity ")

    r = df.index[np.isinf(df).any(1)]

    print(r)

    Output:

    How do you check if a value is infinity in python?

    Method 2: Usenp.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.

    Syntax:

    isfinite(array [, out])

    Example: 

    Python3

    import pandas as pd

    import numpy as np

    data = {'Student ID': [10, 11, 12, 13, 14], 'Age': [

        23, 22, 24, 22, 25], 'Weight': [66, 72, np.inf, 68, -np.inf]}

    df = pd.DataFrame(data)

    d = np.isfinite(df)

    display(d)

    Output:

    How do you check if a value is infinity in python?


    How do you check if there is infinity in pandas?

    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.

    How do you know if a float is infinity in Python?

    Testing for positive infinity, or negative infinity, individually....
    x == float('-inf').
    math. isinf(x) and x < 0..

    How is infinity defined in Python?

    Infinity is defined as something that has no end, therefore is not represented as an integer. We know that all arithmetic operations performed on an infinite value will give an infinite value. It is represented as a float value.

    What is float (' inf ')?

    float('inf') As stated in answer above, float('inf') is used for setting a variable with an infinitely large value.