首页 > 解决方案 > 将一系列浮点数转换为 int - 列表中的某些 NaN 导致错误“无法将浮点 NaN 转换为整数”。如何跳过 NaN?

问题描述

我在 pandas 数据框中有一列非常大的电话号码,它们采用浮点格式:3.52831E+11. 还存在 NaN。

我正在尝试将数字转换为 int,但它抛出了一个错误,即 NaN 无法转换为 int。很公平。但我似乎无法解决这个问题。

这是一个示例:

df = pd.DataFrame({'number':['3.578724e+11','3.568376e+11','3.538884e+11',np.NaN]})


    number
0   3.578724e+11
1   3.568376e+11
2   3.538884e+11
3   NaN


# My first attempt: here's where I try to convert them to int() however I get 'cannot convert float NaN to integer'. 

df['number'] = [int(x) for x in df['number'] if isinstance(x, float)]


# I have also tried the below, but I get SyntaxError: invalid syntax.

df['number'] = [int(x) for x in df['number'] if x not None]


# and then this one, but the error is: TypeError: must be real number, not str

df['number'] = [int(x) for x in df['number'] if not math.isnan(x) and isinstance(x, float)]

我很感激这方面的一些指示。我认为至少其中一个会起作用。

谢谢各位

标签: pythonpandas

解决方案


从 pandas 0.24+ 开始,我们有了Nullable Integer Type。第一步是将您的字符串(对象)转换为浮点数,然后转换为可为空的 int:

df.astype('float').astype(pd.Int64Dtype())                                                                                          

         number
0  357872400000
1  356837600000
2  353888400000
3           NaN

作为速记,你也可以这样做,

df.astype('float').astype('Int64')                                                                                                 

         number
0  357872400000
1  356837600000
2  353888400000
3           NaN

在旧版本上,您唯一的选择是删除 NaN 并转换:

df.dropna(subset=['number']).astype({'number':float}).astype({'number':int})                                                        

         number
0  357872400000
1  356837600000
2  353888400000

推荐阅读