What is numpy.isinf() in Python?

Python’s numpy.isinf() is used to test if an element is a positive/negative infinity or not. It tests an array element-wise and returns a Boolean array as the output.

Syntax

numpy.isinf() is declared as follows:

numpy.isinf(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'isinf'>

In the syntax above, x is the non-optional parameter and the rest are optional parameters.

A universal function (ufunc) is a function that operates on ndarrays in an element-by-element fashion. The inf() method is a universal function.

Parameters

The numpy.isinf() method takes the following compulsory parameter:

  • x [array-like] - input array.

The numpy.isinf() method takes the following optional parameters:

Parameter

Description

out

represents the location into which the output of the method is stored.

where

True value indicates that a universal function should be calculated at this position.

casting

controls the type of datacasting that should occur. The same_kind option indicates that safe casting or casting within the same kind should take place. 

dtype

represents the desired data type of the array.

order

controls the memory layout order of the output function. The option K means reading the elements in the order they occur in memory.

subok

decides if subclasses should be made or not. If True, subclasses will be passed through. 

Return value

numpy.isinf() returns Boolean values True or False depending on the following:

  • It returns True if x is positive infinity or negative infinity

  • It returns False in all other cases

If x is scalar, the return type is also scalar. Else return type is a boolean array.

Examples

The example below shows the use of numpy.isinf() on the elements a and b:

import numpy as np
a = 23
b = np.inf
print (np.isinf(a))
print (np.isinf(b))

The following example shows the use of numpy.isinf() on the array arr1:

import numpy as np
arr1 = np.array([2, -np.inf, 0, np.nan])
print (np.isinf(arr1))

The following example shows the use of numpy.isinf() on the array arr2:

import numpy as np
arr2 = np.array([[1, 2, 3], [np.inf, np.nan, -np.inf]])
print (np.isinf(arr2))

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved