python - 将一系列 float 转换为 int - 列表中的某些 NaN 导致错误 'cannot convert float NaN to integer' 。如何跳过 NaN?

标签 python pandas

我在 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)]

我很感激对此的一些指示。我认为至少其中之一会起作用。

谢谢大家

最佳答案

从 pandas 0.24+ 开始,我们有 Nullable Integer Type 。第一步是将字符串(对象)转换为 float,然后转换为可为空的 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

关于python - 将一系列 float 转换为 int - 列表中的某些 NaN 导致错误 'cannot convert float NaN to integer' 。如何跳过 NaN?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56602596/

相关文章:

python - 推断哪些列是日期时间

python - 如何生成根据另一个数据的数量重复一个数据的 DataFrame?

Python:计算允许联系的列表中项目的最大出现次数

python - 检查其他 Dataframe 上是否存在值

python - 如何将值是列表的系列的值折叠成唯一列表

跳过 Python 预提交单元测试

python - 如何转发/填充 Pandas DataFrame 列/系列中的特定值?

python - 任意数序列的回归测试

python - 如何更改 subprocess.Popen(stdout=None) 中 stdout=None 继承的内容?

python - 使用 endswith 读取文件列表未在列表中找到扩展名