【问题标题】:Python pandas - ValueError: invalid literal for int() with base 10:Python pandas - ValueError:int() 以 10 为底的无效文字:
【发布时间】:2021-12-15 18:18:49
【问题描述】:

我有一个数据框,其中有一列名为 year 的对象格式。我想将对象转换为 int 但我有这个错误:

ValueError: int() 以 10 为底的无效文字:'2021.0'

这是我的代码: data_h_df['year'].astype(str).astype(int)

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    先转换成浮点数,再转换成整数:

    data_h_df['year'].astype(float).astype(int)
    

    如果有NaNs,则使用Int64 表示带有NaNs 的整数:

    data_h_df['year'].astype(float).astype('Int64')
    

    【讨论】:

    • 谢谢你的回答,我试过了,但我有这个错误:ValueError: Cannot convert non-finite values (NA or inf) to integer
    • @Data_ing - 答案已编辑。
    • 谢谢,我试过data_h_df['year'].astype(float).astype('Int64'),它工作正常。
    【解决方案2】:

    将“忽略”分配给“错误”参数。

    >>> data_h_df['year'].astype(float).astype(int, errors='ignore')
    >>> data_h_df['year']
    0    2021.0
    1    2022.0
    2       NaN
    3       2.0
    dtype: float64
    
    

    【讨论】:

      猜你喜欢
      • 2017-11-17
      • 1970-01-01
      • 2020-10-12
      • 2018-03-26
      • 2021-07-23
      • 2021-01-10
      • 2021-01-09
      • 1970-01-01
      • 2016-01-22
      相关资源
      最近更新 更多