Python 将NaN替换为零,将无穷替换为大的有限数字

Python 将NaN替换为零,将无穷替换为大的有限数字

要将NaN替换为零,将无穷替换为大的有限数字,在Python中使用numpy.nan_to_num()方法。该方法返回非有限值替换后的x值。如果copy为False,则可能直接返回x本身。第一个参数是输入数据。第二个参数是copy,设置为True时创建x的副本,设置为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))

示例

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))

输出

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+0.j 0.00000000e+000+0.j]

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程