首页 > 解决方案 > 将对象(字符串)转换为 Int32 时出错:TypeError:对象无法转换为 IntegerDtype

问题描述

尝试将 Pandas 中的对象(字符串)列转换Int32为允许NA值的整数类型时出现以下错误。

df.column = df.column.astype('Int32')

TypeError:对象无法转换为 IntegerDtype

我正在使用熊猫版本:0.25.3

标签: pythonpandas

解决方案


这是已知的错误,如此所述。

解决方法是将 column first 转换floatInt32.

确保在进行转换之前从空格中删除列:

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

推荐阅读