python - Python如何将Series类型:对象转换为int
问题描述
我正在尝试将 Series 对象转换为整数。但我很难做到这一点。每次我尝试某些东西时,我都会遇到一个新错误。
- 我尝试
pd.to_numeric
在解析字符串时使用,错误进行转换None
- 然后我尝试将
None
值替换为NaN
:问题替换
#1.1)
pd.to_numeric(df['Var1'], downcast = 'integer')
ValueError: Unable to parse string "None" at position 44816
#1.2)
df.astype({'Var1':'int64'}).dtypes
TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'
#2)
df['Var1'].astype(str).astype(int)
ValueError: invalid literal for int() with base 10: 'None'
实际结果:dtype:object
预期结果:dtype:int64
解决方案
您似乎"None"
在一个(或多个)单元格中有一个字符串。尝试先将其替换为np.nan
然后转换为数字:
import numpy as np
df = df.replace("None", np.nan).astype({'Var1': float})
请注意,在熊猫版本 <0.24 中,整数列中不能有缺失值(NaN),这就是我建议将其转换为浮点数的原因。
推荐阅读
- c++ - 如何在c ++中在运行时确定模板参数
- java - 使用带有按钮和开关的 CheckBox
- office-js - 有没有办法以编程方式创建一个新的 Range,或者获取 Start 和 End 属性?
- scala - 从表中导出多个文件
- android - 退款后如何撤销 Android 应用内非消耗品购买权利?
- google-apps-script - Google Script 与脚本有冲突
- c++ - 格式化没有这样的文件或目录
- asp.net-mvc - ASP.NET Core MVC ChallengeResult,在重定向的操作方法中未收到 AuthenticationProperties 参数
- r - 如何跨多个列应用复杂的条件更改?
- python - 如何使用 spaCy 编写代码来合并标点符号和短语