【问题标题】:unable to convert float to int in pandas无法在 pandas 中将 float 转换为 int
【发布时间】:2018-11-14 21:59:04
【问题描述】:

我想将具有值 -1.0、0.0 和 Nans 的列转换为 int。 pd.tonumericmyCol.astype 我都试过了

myCol = pd.to_numeric(myCol,downcast='signed', errors = 'coerce')
myCol.astype(np.int64, errors= 'ignore')

这些方法都不起作用。 所需的输入和输出

input: myCol = pd.Series([np.nan, 0.0, -1.0, 0.0, 0.0, 2.0])
output: Nan, 0, -1, 0, 0, 2

谢谢。

【问题讨论】:

  • 你期望NaNint 值是多少?
  • 输入是什么,输出是什么,期望的输出是什么?样本可以帮助我们诊断问题
  • @G.Anderson 对不起。刚刚编辑。
  • 你当前的输出是什么?
  • pandas 的一个不幸特性是任何带有 NaN 的数值列都会自动变成浮点数据类型。您可以转换为字符串并修剪。但是,该列将是数据类型“对象”。

标签: python pandas int


【解决方案1】:

不幸的是,NaN 本身就是一个浮点数(请查看 IEEE 754 浮点标准)。因此,除非您删除带有 NaN 的行,否则您到 int 的转换将始终失败!

否则您使用astype 的方法是正确的。

【讨论】:

    【解决方案2】:

    你可以试试这个来创建字符串:

    myCol.astype(str).str.split('.', expand=True)[0].tolist()
    

    输出:

    ['nan', '0', '-1', '0', '0', '2']
    

    【讨论】:

      猜你喜欢
      • 2021-11-02
      • 2017-03-08
      • 2016-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-13
      • 1970-01-01
      相关资源
      最近更新 更多