【问题标题】:Python How to convert Series type : object to intPython如何将Series类型:对象转换为int
【发布时间】:2019-12-01 08:42:51
【问题描述】:

我正在尝试将 Series 对象转换为整数。但我很难做到这一点。每次我尝试某些东西时,我都会遇到一个新错误。

  1. 我尝试使用pd.to_numeric进行转换,解析字符串None时出错
  2. 然后我尝试用NaN 替换None 值:替换问题

#1.1)

pd.to_numeric(df['Var1'], downcast = 'integer')

ValueError: Unable to parse string "None" at position 44816

#1.2)

df.astype({'Var1':'int64'}).dtypes

TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'

#2)

df['Var1'].astype(str).astype(int)

ValueError: invalid literal for int() with base 10: 'None'

实际结果:dtype:object
预期结果:dtype:int64

【问题讨论】:

    标签: python string pandas int jupyter


    【解决方案1】:

    您似乎在一个(或多个)单元格中有一个字符串"None"。尝试先将其替换为np.nan,然后再转换为数字:

    import numpy as np
    df = df.replace("None", np.nan).astype({'Var1': float})
    

    请注意,在熊猫版本

    【讨论】:

      【解决方案2】:

      试试

      import numpy as np
      df = df.fillna(np.nan)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-12
        • 2015-02-12
        相关资源
        最近更新 更多