Python NumPy 用零替换NaN,并为复杂的输入值填充正无穷

Python NumPy 用零替换NaN,并为复杂的输入值填充正无穷

在这篇文章中,我们将看到如何在Python中对复杂的输入值用零来代替NaN并填充正无穷。

Numpy包为我们提供了numpy.nan_to_num()方法,在Python中用零替换NaN,并为复杂的输入值填充正无穷。这个方法用一个数字替换一个nan值,用我们选择的数字替换正无穷大。让我们详细看看numpy.nan_to_num()的语法。

语法: numpy.nan_to_num(x, copy=True, nan=0.0, posinf=None, neginf=None)

参数:

  • x:类似数组或标量对象。作为输入的数据。
  • copy: 可选的值,布尔值。传递’true’以创建x的副本,或’false’以原地替换数值。默认为’true’。
  • nan:可选的值,int或float.用这个值填充NaN值。如果没有给出值,NaN值将被替换为0.0。
  • posinf:可选的值,int或float。用这个值填充正无穷大的值。如果没有给定值,正无穷值将被替换成一个极大的数字。
  • neginf: 可选的值,int或float.用这个值填入负无穷值。如果没有传递值,负无穷值将被替换成一个非常小的整数。

返回:一个数组对象。

示例 1:

在这个例子中,我们在np.nan和np.inf的帮助下创建了一个虚数的数组。数组的形状是由.shape属性定义的,数组的尺寸是由.ndim定义的。现在我们将使用posinf参数将np.inf替换为9999999的值。

import numpy as np
 
# array of imaginary numbers
array = np.array([complex(np.nan, 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 0.0 and np.inf
# is replaced with 999999
print("After replacement the array is : ",np.nan_to_num(array, posinf = 999999))

输出:

[nan+infj]
Shape of the array is :  (1,)
The dimension of the array is :  1
Datatype of our Array is :  complex128
After replacement the array is :  [0.+999999.j]

示例 2:

在这个例子中,我们要用100的值来代替nan。

import numpy as np
 
# Creating an array of imaginary numbers
array = np.array([complex(np.nan, 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 999999
print("After replacement the array is : ",
      np.nan_to_num(array,nan= 100, posinf = 999999))

输出:

[nan+infj]
Shape of the array is :  (1,)
The dimension of the array is :  1
Datatype of our Array is :  complex128
After replacement the array is :  [100.+999999.j]

示例 3:

在这个例子中,我们要替换nan=100,posinf=999999,neginf=0。

# import package
import numpy as np
 
# Creating an array of imaginary numbers
array = np.array([complex(np.nan, np.inf),-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 999999
print("After replacement the array is : ",
      np.nan_to_num(array,nan= 100, posinf = 999999, neginf=0))

输出:

[ nan+infj -inf +0.j]
Shape of the array is :  (2,)
The dimension of the array is :  1
Datatype of our Array is :  complex128
After replacement the array is :  [100.+999999.j   0.     +0.j]

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程