Pandas: ValueError: cannot convert float NaN to integer 报错
对某列数据作运算时出现如下报错
ValueError: cannot convert float NaN to integer
该报错原因多是在进行数值计算时产生,因计算列内含有非数值型内容NaN
解决方法如下:
- 先确定NaN是否代表空值
print(df[df['x'].isnull()])
- 若非空值,则对其作如下转换
df['x'] = pd.to_numeric(df['x'], errors='coerce')
- 然后将空值删除并转为数值型结构
df = df.dropna(subset=['x'])
df['x']=df['x'].astype(int)