You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何Pandas会将整数转换为float64?如何避免该问题?

问题原因

创建空的Pandas DataFrame时,没有指定任何列的数据类型。当你第一次通过loc给单元格赋值整数1时,Pandas为了保证后续能兼容浮点数、缺失值(NaN)等更灵活的数据,会自动将该列的 dtype 设置为float64,所以整数1会被转换为浮点数1.0存储。

解决方法
  • 初始化时指定列的整数类型
    提前定义列的数据类型,从根源避免自动转换:

    import pandas as pd
    df = pd.DataFrame({'Y': pd.Series(dtype='int64')})
    df.loc['X', 'Y'] = 1
    print(df)
    

    输出会显示整数1,而非1.0。

  • 赋值后手动转换列类型
    如果已经用空DataFrame开始操作,赋值后可以强制转换列的类型:

    import pandas as pd
    df = pd.DataFrame()
    df.loc['X', 'Y'] = 1
    df['Y'] = df['Y'].astype('int64')
    print(df)
    

    要是列里可能出现缺失值(NaN),可以用Pandas的可空整数类型Int64(注意大写I),既保留整数类型又支持缺失值:

    df['Y'] = df['Y'].astype('Int64')
    
  • 直接初始化带数据的DataFrame
    一开始就明确数据、索引和类型,跳过空DataFrame的自动推断步骤:

    import pandas as pd
    df = pd.DataFrame({'Y': [1]}, index=['X'])
    print(df)
    

内容的提问来源于stack exchange,提问作者buhtz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 22:20:40