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

如何用Python和Pandas遍历指定列并修改字符串值?

解决方案

不用手动遍历行,Pandas提供了更高效的向量化字符串操作,直接用str方法就能批量处理整列:

处理单列

以prediction1列为例,一行代码就能完成下划线替换+转小写:

image_predictions['prediction1'] = image_predictions['prediction1'].str.replace('_', ' ').str.lower()

批量处理多列

如果要同时处理prediction1和prediction2,可以循环列名批量操作:

# 指定要处理的列
target_cols = ['prediction1', 'prediction2']
for col in target_cols:
    image_predictions[col] = image_predictions[col].str.replace('_', ' ').str.lower()

你原来代码的问题

  1. 遍历行的操作完全没必要,Pandas的str方法会自动对列中每个元素执行操作,比循环高效得多
  2. 直接用replace('_', ' ')是对整个列的Series对象执行替换,默认是匹配整个字符串替换,不是替换每个下划线——必须用str.replace才是对每个元素的字符串进行逐字符替换

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 08:48:21