在 Python 中用零替換 NaN,用大的有限數替換無窮大


要將 NaN 替換為零,並將無窮大替換為大的有限數,請在 Python 中使用 numpy.nan_to_num() 方法。該方法返回 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([np.inf, -np.inf, np.nan, -128, 128])

顯示陣列 -

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 替換為零,並將無窮大替換為大的有限數,請在 Python 中使用 numpy.nan_to_num() 方法 -

print("\nResult...\n",np.nan_to_num(arr))

示例

import numpy as np

# Creating a numpy array using the array() method
arr = np.array([np.inf, -np.inf, np.nan, -128, 128])

# 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

# The method returns, x, with the non-finite values replaced. If copy is False, this may be x itself.
print("\nResult...\n",np.nan_to_num(arr))

輸出

Our Array...
[ inf -inf nan -128. 128.]

Dimensions of our Array...
1

Datatype of our Array object...
float64

Shape of our Array object...
(5,)

Result...
[ 1.79769313e+308 -1.79769313e+308 0.00000000e+000 -1.28000000e+002 1.28000000e+002]

更新於: 2022年2月25日

306 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.