在Python中用零替換NaN,併為複數輸入值填充正無窮大


要將NaN替換為零,並將無窮大替換為大的有限數,請使用numpy.nan_to_num()方法。此方法返回x,其中非有限值已替換。如果copy為False,則它可能是x本身。第一個引數是輸入資料。第二個引數是copy,是建立x的副本(True)還是就地替換值。就地操作僅在轉換為陣列不需要複製時才會發生。預設為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替換為零,並將無窮大替換為大的有限數,請在Python中使用numpy.nan_to_num()方法。此方法返回x,其中非有限值已替換。如果copy為False,則它可能是x本身:

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

示例

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, posinf = 22222))

輸出

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...
[22222.+0.j 0.+0.j]

更新於:2022年3月1日

瀏覽量:174

啟動你的職業生涯

完成課程獲得認證

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