[英]Numpy: ValueError: cannot convert float NaN to integer (Python)
我想在A
的特定位置插入NaN
。 但是,有一個錯誤。 我附上了預期的輸出。
import numpy as np
from numpy import NaN
A = np.array([10, 20, 30, 40, 50, 60, 70])
C=[2,4]
A=np.insert(A,C,NaN,axis=0)
print("A =",[A])
錯誤是
<module>
A=np.insert(A,C,NaN,axis=0)
File "<__array_function__ internals>", line 5, in insert
File "C:\Users\USER\anaconda3\lib\site-packages\numpy\lib\function_base.py", line 4678, in insert
new[tuple(slobj)] = values
ValueError: cannot convert float NaN to integer
預期的輸出是
[array([10, 20, NaN, 30, 40, NaN, 50, 60, 70])]
為您的float32
數組指定一個類型(或float16
、 float64
等,視情況而定)
import numpy as np
A = np.array([10, 20, 30, 40, 50, 60, 70], dtype=np.float32)
C=[2,4]
A=np.insert(A,C,np.NaN,axis=0)
print("A =",[A])
A = [數組([10., 20., nan, 30., 40., nan, 50., 60., 70.], dtype=float32)]
解決此錯誤的方法是在嘗試將列從浮點數轉換為整數之前處理 NaN 值。
您可以按照以下步驟操作
我們可以使用以下代碼首先識別包含 NaN 值的行:
#print rows in DataFrame that contain NaN in 'rebounds' column print(df[df['rebounds'].isnull()]) points assists rebounds 1 12 7 NaN 5 23 9 NaN
然后,在將列從浮點數轉換為整數之前,我們可以刪除具有 NaN 值的行或將 NaN 值替換為其他值:
方法 1:刪除具有 NaN 值的行
#drop all rows with NaN values df = df.dropna() #convert 'rebounds' column from float to integer df['rebounds'] = df['rebounds'].astype(int) #view updated DataFrame df points assists rebounds 0 25 5 11 2 15 7 10 3 14 9 6 4 19 12 5 6 25 9 9 7 29 4 12 #view class of 'rebounds' column df['rebounds'].dtype dtype('int64')
方法 2:替換 NaN 值
#replace all NaN values with zeros df['rebounds'] = df['rebounds'].fillna(0) #convert 'rebounds' column from float to integer df['rebounds'] = df['rebounds'].astype(int) #view updated DataFrame df points assists rebounds 0 25 5 11 1 12 7 0 2 15 7 10 3 14 9 6 4 19 12 5 5 23 9 0 6 25 9 9 7 29 4 12 #view class of 'rebounds' column df['rebounds'].dtype dtype('int64')
祝你好運
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.