Python中的 numpy.asarray_chkfinite()
numpy.asarray_chkfinite()
函数用于将输入转换为数组,检查 NaN(非数字)或 Infs(无穷大)。输入包括标量、列表、元组列表、元组、元组元组、列表元组和 ndarray。
Syntax : numpy.asarray_chkfinite(arr, dtype=None, order=None)
Parameters :
arr : [array_like] Input data, in any form that can be converted to an float type array. This includes scalar, lists, lists of tuples, tuples, tuples of tuples, tuples of lists and ndarrays.
dtype : By default, the data-type is inferred from the input data.
order : Whether to use row-major (C-style) or column-major (Fortran-style) memory representation. Defaults to ‘C’.
Return : [ndarray] Array interpretation of arr. No copy is performed if the input is already ndarray. If arr is a subclass of ndarray, a base class ndarray is returned.
代码 #1:列表到数组
# Python program explaining
# numpy.asarray_chkfinite() function
import numpy as geek
my_list = [1, 3, 5, 7, 9]
print ("Input list : ", my_list)
out_arr = geek.asarray_chkfinite(my_list, dtype ='float')
print ("output array from input list : ", out_arr)
输出 :
Input list : [1, 3, 5, 7, 9]
output array from input list : [ 1. 3. 5. 7. 9.]
代码#2:元组到数组
# Python program explaining
# numpy.asarray_chkfinite() function
import numpy as geek
my_tuple = ([1, 3, 9], [8, 2, 6])
print ("Input tuple : ", my_tuple)
out_arr = geek.asarray_chkfinite(my_tuple, dtype ='int8')
print ("output array from input tuple : ", out_arr)
输出 :
Input tuple : ([1, 3, 9], [8, 2, 6])
output array from input tuple : [[1 3 9]
[8 2 6]]
注意:如果 arr 包含 NaN(非数字)或 Inf(无穷大), numpy.asarray_chkfinite()
函数会引发ValueError
。
代码#3:
# Python program explaining
# numpy.asarray_chkfinite() function
# when value error occurs
import numpy as geek
my_list = [1, 3, 5, 7, geek.inf, geek.nan]
print ("Input scalar : ", my_scalar)
out_arr = geek.asarray_chkfinite(my_list)
print ("output fortan array from input scalar : ", out_arr)
输出 :
ValueError: array must not contain infs or NaNs