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

Pandas如何删除列中特定字符前内容并将值转换为float类型

问题解决方法

你的代码存在两个核心错误:

  • 分割字符参数错误:你调用split('n', 1)实际要分割的是换行符\n,写错了分割标记导致无法正确截取\n之后的内容
  • 类型转换位置错误:你把astype(float)写在循环体内部,第一次循环仅修改了第一行的三个列值,其余行还包含原始字符串内容,直接转浮点会触发格式错误

最优实现代码

不需要遍历行,用pandas自带的向量化字符串操作即可高效完成需求:

# 提取三个列中\n后的所有内容
matches['one'] = matches['one'].str.split('\n', n=1).str[-1]
matches['ics'] = matches['ics'].str.split('\n', n=1).str[-1]
matches['two'] = matches['two'].str.split('\n', n=1).str[-1]

# 统一转float类型
matches[['one', 'ics', 'two']] = matches[['one', 'ics', 'two']].astype(float)

循环写法修正版

如果你要保留原循环写法,将类型转换移到循环外部,同时修正split参数即可生效:

for index, row in matches.iterrows():
    matches.loc[index, 'one'] = matches.loc[index, 'one'].split('\n', 1)[-1]
    matches.loc[index, 'ics'] = matches.loc[index, 'ics'].split('\n', 1)[-1]
    matches.loc[index, 'two'] = matches.loc[index, 'two'].split('\n', 1)[-1]

# 所有行处理完成后再统一转换类型
matches['one'] = matches['one'].astype(float)
matches['ics'] = matches['ics'].astype(float)
matches['two'] = matches['two'].astype(float)

内容的提问来源于stack exchange,提问作者Gloria Dalla Costa

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 22:24:03