在 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)
在 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]
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP