What is the numpy.asarray_chkfinite() function in Python?

Overview

The asarray_chkfinite() function in Python is used to convert input data to an array. It is also used to raise a ValueError for NaNs or Infs values.

Syntax

numpy.asarray_chkfinite(a, dtype=None, order=None)
Syntax for the asarray_chkfinite() function in Python

Parameter values

The asarray_chkfinite() function takes the following parameter values:

  • a: This is the input data and it is a required parameter value.
  • dtype: This is the data type of the desired output array. The value of dtype is inferred from that of the input data. It is an optional parameter value.
  • order: This represents the memory layout or order of the output array. It takes any of the following: "A", "C", "F", and "K" orders. It is an optional parameter value.

Return value

The asarray_chkfinite() function returns an array interpretation of the input data.

Code

import numpy as np
# creating an input data
a = [1.5, 2.0, 3.1, 4.4, 5]
# converting the input data to an array
myarray = np.asarray_chkfinite(a, dtype = np.int)
print(myarray)

Explanation

  • Line 1: We import the numpy module.
  • Line 4: We create the input data a.
  • Line 7: We call the asarray_chkfinite() function and pass the input data a as an argument to the function. Then, we print the result to the console.

Code

import numpy as np
# creating another input data having nan and inf values
b = [1.5, 2.0, 3.1, 4.4, 5, np.inf, np.nan]
try:
# converting the input data to an array
myarray = np.asarray_chkfinite(b)
print(myarray)
except ValueError:
print("ValueError")

Explanation

We use the try and except block to check for the ValueError just like we did in the previous code example.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources