用Python将NaN替换为零,并为复数输入值填充正无穷大
使用numpy.nan_to_num()方法将NaN替换为零并将无限大值填充为较大的有限数。该方法返回替换非有限值后的x。如果copy参数为False,则可能是x本身。第一个参数是输入数据。第二个参数是copy参数,用于指定是否创建x的一个副本(True)或替换原数据(False)。只有在将数据转换为一个数组时不需要创建一个副本时,替换操作才会就地进行。默认为True。
第三个参数是nan,用于填充NaN值的数值。如果不传入数值,则将NaN值替换为0.0。第四个参数是posinf,用于填充正无穷大值的数值。如果不传入数值,则将正无穷大值替换为a。第五个参数是neginfint,用于填充负无穷大值的数值。如果不传入数值,则将负无穷大值替换为一个非常小的(或负数)数值。
步骤
首先,导入所需的库−
import numpy as np
使用array()方法创建一个numpy数组−
arr = np.array([complex(np.inf, np.nan), np.nan])
显示数组 –
print("Our Array...\n",arr)
检查尺寸 –
print("\nDimensions of our Array...\n",arr.ndim)
获取数据类型 –
print("\nDatatype of our Array object...\n",arr.dtype)
获取形状 –
print("\nShape of our Array object...\n",arr.shape)
使用Python中的numpy.nan_to_num()方法将NaN替换为零,并将无限大替换为大的有限数字。该方法返回替换非有限值后的x。如果copy为False,则可能是x本身。
print("\nResult...\n",np.nan_to_num(arr, posinf = 22222))
示例
import numpy as np
# Creating a numpy array using the array() method
arr = np.array([complex(np.inf, np.nan), np.nan])
# Display the array
print("Our Array...\n",arr)
# Check the Dimensions
print("\nDimensions of our Array...\n",arr.ndim)
# Get the Datatype
print("\nDatatype of our Array object...\n",arr.dtype)
# Get the Shape
print("\nShape of our Array object...\n",arr.shape)
# To replace NaN with zero and infinity with large finite numbers, use the numpy.nan_to_num() method in Python
print("\nResult...\n",np.nan_to_num(arr, posinf = 22222))
输出
Our Array...
[inf+nanj nan +0.j]
Dimensions of our Array...
1
Datatype of our Array object...
complex128
Shape of our Array object...
(2,)
Result...
[22222.+0.j 0.+0.j]