python - 将一系列浮点数转换为 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)]
我很感激这方面的一些指示。我认为至少其中一个会起作用。
谢谢各位
解决方案
从 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
推荐阅读
- vba - 有没有办法在不打开文件的情况下提取访问模块?
- mysql - 在不同的列中排列电影的标题
- entity-framework-6 - 为什么 EF 搜索 NULL 返回 0 结果
- c - 使用'temp'数组在C中水平反射(翻转)图像
- typescript - 如何键入属性和值都来自其他类型的对象
- javascript - Vuex 在页面刷新时没有保持 currentUser 状态
- virtualhost - VirtualHost Alias 使用“/myapp/”加载/重定向,但没有斜杠“/myapp”的错误
- r - 按组计算数据集中各个列的计数和平均值
- angular - Angular - 在兄弟组件中渲染模板
- json - 我应该如何为类似的数据属性准备 JSON?