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

如何在Python DataFrame混合类型列中仅对数值保留两位小数

解决方法

原代码错误分析

  1. 遍历逻辑错误:for i in len(df) 中len(df)是整数,无法直接遍历,即便改成for i in range(len(df)),这种逐行循环的方式在pandas中效率极低,也不推荐。
  2. 类型判断错误:if df['skor_change_w_ts'][i] is float 不能用is判断元素类型,正确写法是isinstance(df['skor_change_w_ts'][i], (int, float)),且要同时覆盖整数、浮点数两种数值类型。
  3. 直接修改元素的问题:逐行修改DataFrame元素容易触发SettingWithCopyWarning,且性能远低于pandas原生的向量化操作。

最简实现代码

处理单列

df['skor_change_w_ts'] = df['skor_change_w_ts'].apply(lambda x: round(x, 2) if isinstance(x, (int, float)) else x)

处理多列

先指定需要处理的列名,再批量操作:

# 替换为你实际需要处理的列名列表
target_cols = ['skor_change_w_ts', 'col1', 'col2']
df[target_cols] = df[target_cols].applymap(lambda x: round(x, 2) if isinstance(x, (int, float)) else x)

说明

  • apply/applymap会遍历目标列的每个元素,仅对整数、浮点数类型执行round(2)操作,字符串类型的"null"会保持原样。
  • 这种方式完全契合pandas的操作习惯,避免了低效循环,同时保留原数据的结构和非数值内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 08:25:27