在 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
使用 array() 方法创建 NumPy 数组 -
arr = np.array([np.inf, -np.inf, np.nan, -128, 128])
显示数组 -
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 替换为零,并将无穷大替换为大的有限数,请在 Python 中使用 numpy.nan_to_num() 方法 -
print("\nResult...\n",np.nan_to_num(arr))示例
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...\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
# The method returns, x, with the non-finite values replaced. If copy is False, this may be x itself.
print("\nResult...\n",np.nan_to_num(arr))输出
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 -1.79769313e+308 0.00000000e+000 -1.28000000e+002 1.28000000e+002]
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP