【问题标题】:why is to_numeric() converting str to float instead of int?为什么 to_numeric() 将 str 转换为 float 而不是 int?
【发布时间】:2020-04-26 14:27:27
【问题描述】:

这里是菜鸟。

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

我正在使用 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

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

哈哈!

【问题讨论】:

  • 请参阅docs 中参数块末尾的注释。完成 .astype(int) 后,只需转换为 int。
  • 你的专栏里有nan吗?
  • 我需要它们是整数,这样我才能与另一个整数列表进行比较。不过这应该不是问题。
  • 是的,列中有'Nan'。

标签: python pandas


【解决方案1】:

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

The default return dtype is float64 or int64 depending on the data supplied. Use the downcast parameter to obtain other dtypes.

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

【讨论】:

  • 我认为这就是我在帖子中描述的 pd.to_numeric(citydata.tcad_id, downcast='integer', errors='coerce') 所做的事情?向下转换是否需要额外的步骤?
【解决方案2】:

可能为时已晚,但您的数据中是否存在“nan”或无穷大?这就是我的问题。您可以尝试这样做:

pd.to_numeric(citydata.tcad_id.replace([np.inf, -np.inf], np.nan).dropna(), 
downcast='integer', errors='coerce')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-11
    • 2018-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-29
    • 2023-01-16
    相关资源
    最近更新 更多