python - 为什么 to_numeric() 将 string 转换为 float 而不是 int ?

标签 python pandas

这里是菜鸟。

我有一个 pandas 数据框,我正在尝试将一列数字从字符串类型转换为整数。但是当我使用 to_numeric() 时,它会转换为 float 。

我正在使用 Jupyter Notebook。

citydata.tcad_id

结果

0      0206180115

2      0125050304

3      0225050137

4      0124000601

         ...    
995    0250300107

996    0217230301

997    0203030703

998    0135070323

999    0204160717

Name: tcad_id, Length: 1000, dtype: object

还有

type(citydata.tcad_id[0])

显示第一个(和后续)条目是...

str

所以我尝试了

pd.to_numeric(citydata.tcad_id, downcast='integer', errors='coerce')

但这会导致

0      206180115.0

1      419120319.0

2      125050304.0

3      225050137.0

4      124000601.0

       ...     

995    250300107.0

996    217230301.0

997    203030703.0

998    135070323.0

999    204160717.0

Name: tcad_id, Length: 1000, dtype: float64

我需要它们是整数,这样我就可以与另一个整数列表进行比较。

哈普!

最佳答案

如果您查看文档 here您将看到以下内容:

默认返回数据类型是 float64 或 int64,具体取决于提供的数据。使用 downcast 参数获取其他数据类型。

看来 pandas 已决定将您的数据转换为 float64。使用 downcast:'integer' 获取整数值。

关于python - 为什么 to_numeric() 将 string 转换为 float 而不是 int ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59656243/

相关文章:

python - 在python中匹配两个 Pandas 数据框的列名

python - vertica/sqlalchemy - 模式公共(public)权限被拒绝

python - 如何将新列添加到按 groupby 分组的分层数据框中

python - 如何以编程方式计算 Chrome 扩展 ID?

python - IndexError 字符串索引超出范围

python - 将字符串转换为没有日期的 Pandas 时间戳

Python Pandas - 年度数据的每周折线图

Python:pandas,解析数学运算

python - Xpath 获取带有子标签的父标签

python - 调整 wxPython 小部件的大小