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

Pandas按条件修改行值失败求助:替换指定行列的特定值

问题解决方法

你的代码错误在于loc的使用语法,loc的第二个参数应该是要修改的列名,而非条件判断。正确的做法是将两个筛选条件组合后放在行索引位置,再指定要修改的industry列。

正确代码写法

分步写法(更清晰)

# 构建筛选条件:同时满足两个列的指定值
mask = (resultdf['fields_of_study'] == "Elektrik ve Elektronik Mühendisliği") & (resultdf["industry"] == "-1")
# 对符合条件的行的industry列赋值
resultdf.loc[mask, 'industry'] = "Defense & Space"

单行写法

resultdf.loc[(resultdf['fields_of_study'] == "Elektrik ve Elektronik Mühendisliği") & (resultdf["industry"] == "-1"), 'industry'] = "Defense & Space"

关键注意点

  • 多条件组合时,每个条件必须用括号()包裹,避免运算符优先级导致的逻辑错误
  • 确认industry列中的-1是字符串类型(你的代码中用了== "-1"),如果是数值类型,需改为== -1

内容的提问来源于stack exchange,提问作者Fatih Oğuzhan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 22:10:35