如何使用isin函数替换pandas DataFrame列中不符合条件的取值
pandas通过isin函数替换非目标取值的实现方法
错误原因
存在两处问题:
- 括号匹配错误:
where方法的所有参数都需要放在where()的括号内部,你的代码提前关闭了where的右括号,导致other、inplace参数游离在方法外,触发语法错误 - 逻辑错误:
partytokeep是isin()执行后返回的布尔掩码(符合目标取值的行返回True,不符合返回False),不需要再加引号作为字符串和原列做等值比较
正确实现代码
# 生成布尔掩码:匹配'democrat'和'republican'两个取值 partytokeep = df['party_detailed'].isin(['democrat', 'republican']) # 不符合掩码条件的取值统一替换为'Others' df['party_detailed'].where(partytokeep, other='Others', inplace=True)
如果不习惯用inplace参数,也可以写成赋值形式:
df['party_detailed'] = df['party_detailed'].where(partytokeep, 'Others')
内容的提问来源于stack exchange,提问作者Serene Tan
相关产品推荐
相关产品推荐

