【问题标题】:I want to change dtype from object to int我想将 dtype 从 object 更改为 int
【发布时间】:2020-10-26 21:57:18
【问题描述】:
df['Value'] = [-2,254.00, 3,452.00, 15,698.00, -6,258.00]

数据类型是对象。我想将它们转换为整数,但出现错误

【问题讨论】:

    标签: python pandas anaconda3


    【解决方案1】:

    使用df.astype:

    In [2329]: df['Value'] = df['Value'].astype(int)
    
    In [2329]: df['Value']
    Out[2329]: 
    0     -2
    1    254
    2      3
    3    452
    4     15
    5    698
    6     -6
    7    258
    Name: Value, dtype: int64
    

    【讨论】:

    • 你好,数字如下 0 -2,254.00 1 3,452.00 2 15,698.00 3 -6,258.00
    • 嗨,我已经显示了输出。 df['Value'] = df['Value'].astype(int)这是我的命令。
    • @SimbarasheNM 如果答案有帮助,请accept它。
    【解决方案2】:

    你可以试试下面的代码:

    df['Value'] = df['Value'].astype(dtype='int64')
    

    【讨论】:

    • 它给出了错误 ValueError: invalid literal for int() with base 10: '1,000.00'
    【解决方案3】:

    pd.to_numericerrors='coerce' 一起使用

    df['Value'] = pd.to_numeric(df['Value'], errors='coerce')
    

    【讨论】:

    • 谢谢,但代码正在删除所有负值
    • 不客气,你能显示预期的输出吗?
    • 对不起。预期输出将是两个额外的列 Index Value Value1 Value2 0 -2,254.00 2254.00 0 1 3,452.00 0 3452.00 2 15,698.00 0 15,698.00 3 -6,258.00 6,258.00 0 所以负数进入列 Value1 没有 - 符号,正数进入 Value2
    猜你喜欢
    • 2013-01-06
    • 1970-01-01
    • 2020-09-15
    • 2017-01-03
    • 2021-01-09
    • 2020-07-08
    • 1970-01-01
    • 2021-08-08
    • 2019-05-23
    相关资源
    最近更新 更多