Python中用零替換NaN並填充負無窮值


在Python中,要將NaN替換為零,並將無窮大替換為大的有限數,可以使用numpy.nan_to_num()方法。此方法返回x,其中非有限值已被替換。如果copy為False,則這可能是x本身。第一個引數是輸入資料。第二個引數是copy,是建立x的副本(True)還是就地替換值(False)。只有當轉換為陣列不需要複製時,才會進行就地操作。預設為True。

第三個引數是nan,用於填充NaN值的值。如果沒有傳入值,則NaN值將被替換為0.0。第四個引數posinf,用於填充正無窮值的值。如果沒有傳入值,則正無窮值將被替換為a。第五個引數neginf,用於填充負無窮值的值。如果沒有傳入值,則負無窮值將被替換為一個非常小(或負)的數。

步驟

首先,匯入所需的庫:

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

print("\nResult...\n",np.nan_to_num(arr, neginf = 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...\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, neginf = 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...
[ 1.79769313e+308 2.22220000e+004 0.00000000e+000 -1.28000000e+002
1.28000000e+002]

更新於:2022年3月1日

481 次瀏覽

啟動你的職業生涯

完成課程獲得認證

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