将对象(字符串)转换为 Int32 时出错:TypeError:对象无法转换为 IntegerDtype [英] Error converting object (string) to Int32: TypeError: object cannot be converted to an IntegerDtype
问题描述
我在尝试将 Pandas 中的对象(字符串)列转换为 Int32
时遇到以下错误,Int32
是允许 NA
值的整数类型.
df.column = df.column.astype('Int32')
<块引用>
TypeError: 对象无法转换为 IntegerDtype
我使用的是熊猫版本:0.25.3
It's known bug, as defined 此处.
解决方法是先将列转换为 float
,然后再转换为 Int32
.
确保在进行转换之前从空格中去除您的列:
df.column = df.column.str.strip()
比做转换:
df.column = df.column.astype('float') # 先转为浮点型,再转为 intdf.column = df.column.astype('Int32')
或更简单:
df.column = df.column.astype('float').astype('Int32') # 或 Int64
I get following error while trying to convert object (string) column in Pandas to Int32
which is integer type that allows for NA
values.
df.column = df.column.astype('Int32')
TypeError: object cannot be converted to an IntegerDtype
I'm using pandas version: 0.25.3
It's known bug, as explained here.
Workaround is to convert column first to float
and than to Int32
.
Make sure you strip your column from whitespaces before you do conversion:
df.column = df.column.str.strip()
Than do conversion:
df.column = df.column.astype('float') # first convert to float before int
df.column = df.column.astype('Int32')
or simpler:
df.column = df.column.astype('float').astype('Int32') # or Int64
这篇关于将对象(字符串)转换为 Int32 时出错:TypeError:对象无法转换为 IntegerDtype的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!