numpy.asarray_chkfinite() in Python
numpy.asarray_chkfinite() in Python
The numpy.asarray_chkfinite() function converts the input to an array, checking for NaNs or Infs.
Syntax
numpy.asarray_chkfinite(a, dtype=None, order=None)
Parameter
a : This parameter represents an input data, which can be in the form of lists, tuples, lists of tuples, tuples of tuples and ndarrays,etc,.that can be converted to an array.
dtype : It is an optional parameter, and by default, the data-type is inferred from the input data.
order : This parameter decides whether to use row-major (C-style) or column-major (Fortran-style) memory representation and by default, the ‘C-style’ is selected.
Return
This function returns an array interpretation of parameter ‘a’. If ‘a’ is a subclass of ndarray, a base class ndarray is returned.
Raises
This function raises a ValueError if the parameter ‘a’ contains NaN (Not a Number) or Inf (Infinity).
Example 1
# Python program explaining # numpy.asarray_chkfinite() function import numpy as np inp_list = [19, 13, 25, 37] print ("Input List: ", inp_list) out_arr = np.asarray_chkfinite(inp_list) print ("Output array: ", out_arr)
Output
Input List: [19, 13, 25, 37] Output array: [19 13 25 37]
Example 2
# Python program explaining # numpy.asarray_chkfinite() function import numpy as np inp_scalar = 500 print ("Input scalar: ", inp_scalar) out_arr = np.asarray_chkfinite(inp_scalar, dtype ='float') print ("Output array: ", out_arr)
Output
Input scalar: 500 Output array: 500.0
Example 3 : When value error occurs
# Python program explaining # numpy.asarray_chkfinite() function import numpy as np #passing NAN value inp_list = [19, 13, 25, 37, np.inf, np.nan] print ("Input List: ", inp_list) out_arr = np.asarray_chkfinite(inp_list) print ("Output array: ", out_arr)
Output
Input List: [19, 13, 25, 37, inf, nan] Traceback (most recent call last): File "main.py", line 10, in <module> out_arr = np.asarray_chkfinite(inp_list) File "/usr/lib/python3/dist-packages/numpy/lib/function_base.py", line 595, in asarray_chkfinite "array must not contain infs or NaNs") ValueError: array must not contain infs or NaNs