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

Har*_*vey 13 python pandas

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

df.column = df.column.astype('Int32')
Run Code Online (Sandbox Code Playgroud)

类型错误:对象无法转换为 IntegerDtype

我正在使用熊猫版本:0.25.3

Har*_*vey 23

这是已知的错误,如解释here

解决方法是先将 column 转换为 ,float然后再转换为Int32

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

df.column = df.column.str.strip()
Run Code Online (Sandbox Code Playgroud)

比做转换:

df.column = df.column.astype('float')  # first convert to float before int
df.column = df.column.astype('Int32')
Run Code Online (Sandbox Code Playgroud)

或更简单:

 df.column = df.column.astype('float').astype('Int32') # or Int64
Run Code Online (Sandbox Code Playgroud)

  • 令人震惊的是,一年后这个错误仍然存​​在。 (5认同)
  • [修复](https://github.com/pandas-dev/pandas/pull/43949) 看起来预计适用于 1.4 (2认同)