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

如何在Pandas DataFrame中将非指定值替换为'other'分类?

解决Pandas中替换非指定值为other的问题

你可以用Pandas的where或mask方法快速实现需求,这两个方法能精准保留指定值、替换其余内容,以下是具体实现:

先创建示例DataFrame

import pandas as pd

df = pd.DataFrame({
    'id': [1,2,3,4,5,6],
    'answer': ['Yes', 'Maybe', 'No', 'idk', 'wtf', 'wth']
})

方法1:严格匹配指定字符串

如果只需要保留Yes、No、Maybe这三个精确值,其他内容替换为other:

# 定义允许保留的取值集合
allowed_answers = {'Yes', 'No', 'Maybe'}
# 使用where:条件满足时保留原值,否则替换为'other'
df['answer'] = df['answer'].where(df['answer'].isin(allowed_answers), 'other')

方法2:不区分大小写匹配

如果需要兼容yes、YES、mAYbe等大小写变体,保留原合法值的同时替换其他内容:

# 转成小写后判断是否在目标集合,保留原字符串格式
df['answer'] = df['answer'].where(df['answer'].str.lower().isin({'yes', 'no', 'maybe'}), 'other')

等价方法:使用mask

mask和where逻辑相反,取反条件后也能实现相同效果:

df['answer'] = df['answer'].mask(~df['answer'].isin(allowed_answers), 'other')

执行后你的DataFrame会变成:

id  answer
0   1     Yes
1   2   Maybe
2   3      No
3   4   other
4   5   other
5   6   other

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 17:30:18