在Python中用零替換NaN,併為複數輸入值填充負無窮大
要將NaN替換為零,並將無窮大替換為較大的有限數,請在Python中使用numpy.nan_to_num()方法。此方法返回x,其中非有限值已替換。如果copy為False,則這可能是x本身。第一個引數是輸入資料。第二個引數是copy,是否建立x的副本(True)或就地替換值。就地操作僅在轉換為陣列不需要複製時發生。預設為True。
第三個引數是nan,用於填充NaN值的值。如果沒有傳遞值,則NaN值將被替換為0.0。第四個引數posinf,用於填充正無窮大值的值。如果沒有傳遞值,則正無窮大值將被替換為一個。第五個引數neginf,用於填充負無窮大值的值。如果沒有傳遞值,則負無窮大值將被替換為一個非常小的(或負的)數。
步驟
首先,匯入所需的庫:
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)
要將NaN替換為零,並將無窮大替換為較大的有限數,請使用numpy.nan_to_num()方法:
print("
Result...
",np.nan_to_num(arr, neginf = 4444))示例
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, neginf = 4444))輸出
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 4.44400000e+003 0.00000000e+000 -1.28000000e+002 1.28000000e+002]
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP