Python 将对象(字符串)转换为Int32:TypeError:对象无法转换为IntegerType时出错

Python 将对象(字符串)转换为Int32:TypeError:对象无法转换为IntegerType时出错,python,pandas,Python,Pandas,尝试将Pandas中的object(string)列转换为Int32,这是允许NA值的整数类型时,出现以下错误 df.column = df.column.astype('Int32') TypeError:无法将对象转换为IntegerDtype 我正在使用pandas版本:0.25.3如前所述,这是一个已知的bug 解决方法是首先将列转换为float,然后再转换为Int32 在进行转换之前,请确保将列从空白中删除: df.column = df.column.str.strip() df

尝试将Pandas中的object(string)列转换为
Int32
,这是允许
NA
值的整数类型时,出现以下错误

df.column = df.column.astype('Int32')
TypeError:无法将对象转换为IntegerDtype


我正在使用pandas版本:0.25.3

如前所述,这是一个已知的bug

解决方法是首先将列转换为
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.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

我个人使用
df=df.astype({I:type_dict[I]for I in header},errors='ignore')
来处理这个问题。请注意,
属性错误
将忽略所有类型的警告。虽然它非常不雅观,可能会导致其他严重错误,但它确实可以将
np.NAN
类似'100`
int-like 100
的int字符串转换为pandas.int。
希望这能对您有所帮助。

从v0.24开始,您可以使用:
df['col']=df['col'].astype(pd.Int32Dtype())


编辑:我应该提到这属于文档。文档还指定了其他可为空的整数类型(即Int64Dtype、Int8Dtype、UInt64Dtype等)。

Haolin,您建议的方法返回NameError:名称“header”未定义首先转换为float,然后使用它,这一错误在一年后仍然存在。