在Python中用0替换NaN并填充负无穷值
在这篇文章中,我们将介绍如何在Python中使用NumPy将NaN替换为零并填充负无穷值。
示例
输入: [nan -inf 5.] 。
输出: [0.00000e+00 9.99999e+05 5.00000e+00]
解释:用0代替NaN,用任何值代替负inf。
numpy.nan_to_num 方法
numpy.nan_to_num方法用于用0替换Nan值,它用用户定义的值或一个大的正数来填充负无穷大的值。 neginf是用于此目的的关键字。
语法: numpy.nan_to_num(arr, copy=True)
参数:
- arr : [array_like] 输入数据。
- copy : [bool, optional] 默认为True。
返回:新的数组,其形状与arr相同,并且Arr中元素的dtype精度最高。
示例 1:
在这个例子中,使用numpy.array()方法创建了一个数组,它由np.nan、负无穷和正无穷组成。数组的形状、数据类型和尺寸可以通过.shape、.dtype和.ndim属性找到。这里,使用nan参数将np.nan替换为100,使用neginf参数将负无穷替换为999999。
# import package
import numpy as np
# Creating an array of imaginary numbers
array = np.array([np.nan,-np.inf,5])
print(array)
# shape of the array is
print("Shape of the array is : ",array.shape)
# dimension of the array
print("The dimension of the array is : ",array.ndim)
# Datatype of the array
print("Datatype of our Array is : ",array.dtype)
# np.nan is replaced with 0 and
# negative infinity is replaced with 999999
print("After replacement the array is : ",
np.nan_to_num(array,nan= 0, neginf=999999))
输出:
[ nan -inf 5.]
Shape of the array is : (3,)
The dimension of the array is : 1
Datatype of our Array is : float64
After replacement the array is : [0.00000e+00 9.99999e+05 5.00000e+00]
示例 2:
在这个例子中,我们要在复数和整数的帮助下创建一个数组。在这里,使用nan参数将np.nan替换为100,使用posinf参数将np.inf替换为100000,使用neginf参数将负无穷替换为99999。
# import package
import numpy as np
# Creating an array of imaginary numbers
array = np.array([complex(np.nan, -np.inf),1,2, np.inf])
print(array)
# shape of the array is
print("Shape of the array is : ",array.shape)
# dimension of the array
print("The dimension of the array is : ",array.ndim)
# Datatype of the array
print("Datatype of our Array is : ",array.dtype)
# np.nan is replaced with 100 and np.inf is
# replaced with 100000 negative infinity is replaced with 999999
print("After replacement the array is: ",
np.nan_to_num(array,nan= 100, posinf = 100000, neginf=999999))
输出:
[nan-infj 1. +0.j 2. +0.j inf +0.j]
Shape of the array is : (4,)
The dimension of the array is : 1
Datatype of our Array is : complex128
After replacement the array is : [1.e+02+999999.j 1.e+00 +0.j 2.e+00 +0.j 1.e+05 +0.j]