[英]Numpy: ValueError: cannot convert float NaN to integer (Python)
I want to insert NaN
at specific locations in A
.我想在A
的特定位置插入NaN
。 However, there is an error.但是,有一个错误。 I attach the expected output.我附上了预期的输出。
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])
The error is错误是
<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
The expected output is预期的输出是
[array([10, 20, NaN, 30, 40, NaN, 50, 60, 70])]
Designate a type for your array of float32
(or float16
, float64
, etc. as appropriate)为您的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 = [array([10., 20., nan, 30., 40., nan, 50., 60., 70.], dtype=float32)] A = [数组([10., 20., nan, 30., 40., nan, 50., 60., 70.], dtype=float32)]
The way to fix this error is to deal with the NaN values before attempting to convert the column from a float to an integer.解决此错误的方法是在尝试将列从浮点数转换为整数之前处理 NaN 值。
you can follow the steps as follows您可以按照以下步骤操作
We can use the following code to first identify the rows that contain NaN values:我们可以使用以下代码首先识别包含 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
We can then either drop the rows with NaN values or replace the NaN values with some other value before converting the column from a float to an integer:然后,在将列从浮点数转换为整数之前,我们可以删除具有 NaN 值的行或将 NaN 值替换为其他值:
Method 1: Drop Rows with NaN Values方法 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')
Method 2: Replace NaN Values方法 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')
good luck祝你好运
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.