用 Python 將 NaN 替換為零,並將正無窮大值填充


在 Python 中,要將 NaN 替換為零,並將無窮大替換為大的有限數,可以使用 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...
",arr)

檢查維度:

print("
Dimensions of our Array...
",arr.ndim)

獲取資料型別:

print("
Datatype of our Array object...
",arr.dtype)

獲取形狀:

print("
Shape of our Array object...
",arr.shape)

在 Python 中,要將 NaN 替換為零,並將無窮大替換為大的有限數,可以使用 numpy.nan_to_num() 方法:

print("
Result...
",np.nan_to_num(arr, posinf = 22222))

示例

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...
",arr) # Check the Dimensions print("
Dimensions of our Array...
",arr.ndim) # Get the Datatype print("
Datatype of our Array object...
",arr.dtype) # Get the Shape print("
Shape of our Array object...
",arr.shape) # To replace NaN with zero and infinity with large finite numbers, use the numpy.nan_to_num() method in Python print("
Result...
",np.nan_to_num(arr, posinf = 22222))

輸出

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...
[ 2.22220000e+004 -1.79769313e+308 0.00000000e+000 -1.28000000e+002
1.28000000e+002]

更新於:2022年2月28日

2K+ 次瀏覽

啟動你的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.