Test array values for finiteness and store the result in a new location in Numpy

NumpyServer Side ProgrammingProgramming

To test array values for finiteness, use the numpy.isfinite() method in Python Numpy. The new location where we will store the result is a new array. Returns True where x is not positive infinity, negative infinity, or NaN; false otherwise. This is a scalar if x is a scalar.

This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.

Steps

At first, import the required library −

import numpy as np

Create an array with some inf values −

arr = np.array([1, 2, 10, 50, -np.inf, 0., np.inf])

Display the array −

print("Array...\n", arr)

Get the type of the array −

print("\nOur Array type...\n", arr.dtype)

Get the dimensions of the Array −

print("\nOur Array Dimensions...\n",arr.ndim)

Get the number of elements in the Array −

print("\nNumber of elements...\n", arr.size)

Create another array with the same shape to store the result −

arrRes = np.array([5, 5, 5, 5, 5, 5, 5])

To test array values for finiteness, use the numpy.isfinite() method in Python Numpy. The new location where we will store the result is arrRes −

print("\nTest array for finiteness...\n",np.isfinite(arr, arrRes))

Check the value of the new array where our result is stored: −

print("\nResult...\n",arrRes)

Example

import numpy as np

# Create an array with some inf values
arr = np.array([1, 2, 10, 50, -np.inf, 0., np.inf])

# Display the array
print("Array...\n", arr)

# Get the type of the array
print("\nOur Array type...\n", arr.dtype)

# Get the dimensions of the Array
print("\nOur Array Dimensions...\n",arr.ndim)

# Get the number of elements in the Array
print("\nNumber of elements...\n", arr.size)

# Create another array with the same shape to store the result
arrRes = np.array([5, 5, 5, 5, 5, 5, 5])

# To test array values for finiteness, use the numpy.isfinite() method in Python Numpy
# The new location where we will store the result is arrRes
print("\nTest array for finiteness...\n",np.isfinite(arr, arrRes))

# Check the value of the new array where our result is stored
print("\nResult...\n",arrRes)

Output

Array...
[ 1. 2. 10. 50. -inf 0. inf]

Our Array type...
float64

Our Array Dimensions...
1

Number of elements...
7

Test array for finiteness...
[1 1 1 1 0 1 0]

Result...
[1 1 1 1 0 1 0]
raja
Updated on 07-Feb-2022 11:28:29

Advertisements