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

如何在原DataFrame中按条件替换Column A的取值?

数据修正解决方案

原始数据

Column AColumn B
Police1
other0
Ambulance0
Police1
other0
Ambulance1
Police1
other1
Ambulance1

修正规则

检测到数据录入错误,需按以下规则修正:所有Column B取值为1的行,Column A需设为“Police”(即若Column A不为“Police”且Column B等于1,将Column A更新为“Police”)。

问题分析

你执行的命令 df.loc[(df['Column_A'] !="Police") & (df['Column_B']==1)] 仅返回符合条件的DataFrame子集,并未对原数据进行修改。

正确命令

直接在原数据集上完成值的替换,使用.loc进行赋值操作即可:

# 精准匹配修正条件(仅修改Column A非Police且Column B为1的行)
df.loc[(df['Column_A'] != "Police") & (df['Column_B'] == 1), 'Column_A'] = "Police"

# 更简洁的写法(完全符合规则中"所有Column B为1的行设为Police"的要求)
df.loc[df['Column_B'] == 1, 'Column_A'] = "Police"

修正后目标数据

Column AColumn B
Police1
other0
Ambulance0
Police1
other0
Police1
Police1
Police1
Police1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 08:40:41