Python 将NaN替换为零,并用复数输入值填充负无穷大
要将NaN替换为零,并将无限大值替换为大的有限数字,在Python中使用numpy.nan_to_num()方法。该方法返回替换了非有限值的x。如果copy为False,则可能是x本身。第一个参数是输入数据。第二个参数是copy,表示是否创建x的副本(True)或替换原地的值。只有在不需要复制时,才会发生原地操作。默认为True。
第三个参数是nan,用于填充NaN值的值。如果没有传递值,则NaN值将被替换为0.0。第四个参数是posinf,用于填充正无穷大值的值。如果没有传递值,则正无穷大值将被替换为一个值。第五个参数是neginf,用于填充负无穷大值的值。如果没有传递值,则负无穷大值将被替换为一个非常小(或负)的数。
步骤
首先,导入所需的库 –
import numpy as np
使用array()方法创建一个numpy数组 −
arr = np.array([np.inf, -np.inf, np.nan, -128, 128])
显示数组 –
print("Our Array...
",arr)
检查尺寸 –
print("
Dimensions of our Array...
",arr.ndim)
获取数据类型 –
print("
Datatype of our Array object...
",arr.dtype)
获得形状−
print("
Shape of our Array object...
",arr.shape)
将NaN替换为零,并将无穷大替换为较大的有限数字,请使用numpy.nan_to_num()方法 –
print("
Result...
",np.nan_to_num(arr, neginf = 4444))
示例
import numpy as np
# Creating a numpy array using the array() method
arr = np.array([np.inf, -np.inf, np.nan, -128, 128])
# Display the array
print("Our Array...
",arr)
# Check the Dimensions
print("
Dimensions of our Array...
",arr.ndim)
# Get the Datatype
print("
Datatype of our Array object...
",arr.dtype)
# Get the Shape
print("
Shape of our Array object...
",arr.shape)
# To replace NaN with zero and infinity with large finite numbers, use the numpy.nan_to_num() method in Python
print("
Result...
",np.nan_to_num(arr, neginf = 4444))
输出
Our Array...
[ inf -inf nan -128. 128.]
Dimensions of our Array...
1
Datatype of our Array object...
float64
Shape of our Array object...
(5,)
Result...
[ 1.79769313e+308 4.44400000e+003 0.00000000e+000 -1.28000000e+002
1.28000000e+002]