用大有限数替换Python中的无穷大,并用NaN填充复杂的输入值
要用零替换NaN,并用大有限数替换无穷大,在Python中使用numpy.nan_to_num()方法。该方法返回用非有限值替换的x。如果copy为False,则可能是x本身。第一个参数是输入数据。第二个参数是copy,用于创建x的副本(True)或在原地替换值(False)。仅当强制转换为数组不需要副本时,才会进行就地操作。默认为True。
第三个参数是nan,用于填充NaN值的值。如果没有传递值,则NaN值将被替换为0.0。第四个参数posinf,用于填充正无穷大值的值。如果没有传递值,则正无穷大值将被替换为a。第五个参数neginfint,用于填充负无穷大值的值。如果没有传递值,则负无穷大值将被替换为非常小的(或负)数。
步骤
首先,导入所需的库−
import numpy as np
创建一个numpy数组使用array()方法−
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)
将 NaN 替换为零,将无穷大替换为大有限数,请使用 numpy.nan_to_num() 方法-。
print("\nResult...\n",np.nan_to_num(arr, nan = 11111))
示例
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, nan = 11111))
输出
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...
[1.79769313e+308+11111.j 1.11110000e+004 +0.j]