使用Python中的NumPy,用大的有限数代替无穷大,并为复杂的输入值填充NaN

使用Python中的NumPy,用大的有限数代替无穷大,并为复杂的输入值填充NaN

在这篇文章中,我们将介绍如何在Python中使用NumPy为复杂的输入值和大的有限数填充Nan。

示例:

输入: [complex(np.nan,np.inf)]

输出: [1000.+1.79769313e+308j]

解释:用复数值代替Nan,用大的有限值代替无限值。

numpy.nan_to_num 方法

numpy.nan_to_num方法用于用0替换Nan值,用用户定义的值或大正数填充正无穷和负无穷的值。 neginf是用于此目的的关键词。

语法: numpy.nan_to_num(arr, copy=True)

参数:

  • arr: [array_like] 输入数据。
  • copy: [bool, optional] 默认为True。

返回:新的数组,其形状与arr相同,并且Arr中元素的dtype精度最高。

示例 1:

在这个例子中,使用numpy.array()方法创建了一个数组,它由np.nan和正无穷组成。数组的形状、数据类型和尺寸可以通过.shape, .dtype , 和 .ndim属性找到。这里,使用nan参数将np.nan替换为1000,而n infinity则替换为一个大的有限数。

# import package
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 1000 and
#  infinity is replaced with a large positive number
print("After replacement the array is : ",
      np.nan_to_num(array,nan= 1000))

输出:

[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 :  [1000.+1.79769313e+308j]

示例 2:

在这个例子中,正无穷被替换为一个用户定义的值。

# import package
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 1000 and
#  infinity is replaced with a large positive number
print("After replacement the array is : ",
      np.nan_to_num(array,nan= 1000))

输出:

[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 :  [1000.+99999.j]

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

Numpy教程