修复ValueError无法将浮点数NaN转换为整数的两种方法

2,046 阅读2分钟

在使用pandas时,你可能遇到的一个错误是:

ValueError: cannot convert float NaN to integer

当你试图将pandas DataFrame中的一列从浮点数转换为整数,但该列却包含NaN值时,就会出现这个错误。

下面的例子展示了如何在实践中解决这个错误。

如何重现该错误

假设我们创建了以下的pandas DataFrame:

import pandas as pd
import numpy as np

#create DataFrame
df = pd.DataFrame({'points': [25, 12, 15, 14, 19, 23, 25, 29],
                   'assists': [5, 7, 7, 9, 12, 9, 9, 4],
                   'rebounds': [11, np.nan, 10, 6, 5, np.nan, 9, 12]})

#view DataFrame
df

        points	assists	 rebounds
0	25	5	 11
1	12	7	 NaN
2	15	7	 10
3	14	9	 6
4	19	12	 5
5	23	9	 NaN
6	25	9	 9
7	29	4	 12

目前'rebounds'列的数据类型是'float':

#print data type of 'rebounds' column
df['rebounds'].dtype

dtype('float64')

假设我们试图将'rebounds'列从浮点数转换为整数:

#attempt to convert 'rebounds' column from float to integer
df['rebounds'] = df['rebounds'].astype(int)

ValueError: cannot convert float NaN to integer 

我们收到一个ValueError,因为'rebounds'列中的NaN值不能被转换为整数值。

如何修复该错误

解决这个错误的方法是在试图将该列从浮动值转换为整数之前处理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')

请注意,这两种方法都允许我们避免ValueError,并成功地将浮动列转换为整数列。

其他资源

下面的教程解释了如何修复Python中的其他常见错误。

如何修复:列重叠但没有指定后缀
如何修复:'numpy.ndarray'对象没有属性'append'
如何修复:如果使用所有标量值,必须传递一个索引