在 Python 中用較大的有限數替換無窮大,併為複雜的輸入值填充 NaN
在Python中,可以使用numpy.nan_to_num()方法將NaN替換為零,並將無窮大替換為較大的有限數。該方法返回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([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]
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP