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

Python中如何去除DataFrame列M的.0后缀?

DataFrame列去除.0后缀的解决方法

核心操作方案

  • 先确认转换是否真的失败
    执行df['M'].astype('int64')后,先检查列的实际类型:

    df['M'] = df['M'].astype('int64')
    print(df['M'].dtype)
    

    若输出为int64,说明类型已成功转换,value_counts()显示的.0只是pandas的输出格式问题,无需额外处理。如果想让输出显示为纯整数,可以格式化输出结果:

    count_result = df['M'].value_counts().reset_index()
    count_result.columns = ['M', 'count']
    count_result['M'] = count_result['M'].astype(int)
    print(count_result)
    
  • 强制转换整数类型
    若astype方法未生效,试试用pd.to_numeric指定向下转换:

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

    转换前可以先验证所有值都是整数型浮点数:

    assert df['M'].apply(lambda x: x.is_integer()).all(), "列中存在非整数值,无法直接转整数"
    
  • 转为字符串彻底去除.0
    如果需要将值作为字符串使用(比如导出文本),可以先转整数再转字符串:

    df['M'] = df['M'].astype(int).astype(str)
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 12:58:11