python - 将对象(字符串)转换为 Int32 时出错:TypeError:对象无法转换为 IntegerDtype
问题描述
尝试将 Pandas 中的对象(字符串)列转换Int32
为允许NA
值的整数类型时出现以下错误。
df.column = df.column.astype('Int32')
TypeError:对象无法转换为 IntegerDtype
我正在使用熊猫版本:0.25.3
解决方案
这是已知的错误,如此处所述。
解决方法是将 column first 转换float
为Int32
.
确保在进行转换之前从空格中删除列:
df.column = df.column.str.strip()
比转换:
df.column = df.column.astype('float') # first convert to float before int
df.column = df.column.astype('Int32')
或更简单:
df.column = df.column.astype('float').astype('Int32') # or Int64
推荐阅读
- mysql - 当列和表被定义时,列是未知的?
- php - 如何打印 SimpleXMLElement 对象的特定数组元素
- oracle - 表中的分层首选项
- python - pymongo - “OperationFailure:管道阶段规范对象必须包含一个字段”
- python - C# 返回“C:\Windows\Sysnative”作为无效目录,但 python 没有
- typescript - 在 Typescript 中控制类型级别的“评估”
- lua - 使用 fiber.yield() 和 fiber.testcancel() 的 Tarantool 纤维行为
- python - Python Pandas 丢弃列耗尽资源 - 被杀死
- html - 为什么移动浏览器不支持我的 CSS?
- excel - Excel VBA从旧的2张工作表创建一个新工作簿(+数字作为值而不是公式)