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

能否用pandas.replace替换DataFrame列中除指定值外的所有值?

问题:替换DataFrame指定列的非目标值为'Other'

假设现有如下DataFrame:

age education       marital_status  occupation  race    sex     native_country
1   37  Non-grad        Married         Sales       Other   Female  ?
2   39  HS-grad         Married         Sales       Other   Female  Dominican-Republic
3   29  HS-grad         Married         Sales       White   Female  United-States
4   64  HS-grad         Married         Sales       White   Female  United-States
5   31  HS-grad         Married         Sales       White   Female  United-States
6   53  HS-grad         Married         Sales       White   Female  United-States
7   56  HS-grad         Married         Sales       White   Female  United-States
8   28  Bachelors       Married         Sales       White   Female  United-States
9   52  Some-college    Married         Sales       White   Female  Canada
10  23  Some-college    Married         Sales       White   Female  United-States

需要将native_country列中所有非United-States的值替换为Other,得到如下期望输出:

age education       marital_status  occupation  race    sex     native_country
1   37  Non-grad        Married         Sales       Other   Female  Other
2   39  HS-grad         Married         Sales       Other   Female  Other
3   29  HS-grad         Married         Sales       White   Female  United-States
4   64  HS-grad         Married         Sales       White   Female  United-States
5   31  HS-grad         Married         Sales       White   Female  United-States
6   53  HS-grad         Married         Sales       White   Female  United-States
7   56  HS-grad         Married         Sales       White   Female  United-States
8   28  Bachelors       Married         Sales       White   Female  United-States
9   52  Some-college    Married         Sales       White   Female  Other
10  23  Some-college    Married         Sales       White   Female  United-States

请问能否使用pandas.replace实现该需求?如果不能,应该如何操作?


解答

可以用pandas.replace实现,同时还有更简洁高效的替代方案

1. 使用replace实现

通过传入lambda表达式匹配非目标值,完成替换:

import pandas as pd

# 假设df是你的DataFrame
df['native_country'] = df['native_country'].replace(
    to_replace=lambda x: x != 'United-States',
    value='Other',
    regex=False
)

这种方式会遍历列中每个元素,判断是否不等于United-States,是则替换为Other。

2. 更高效的where方法

where方法会保留满足条件的元素,不满足的替换为指定值,代码更简洁:

df['native_country'] = df['native_country'].where(df['native_country'] == 'United-States', 'Other')

3. 相反逻辑的mask方法

mask与where逻辑相反,满足条件的元素会被替换:

df['native_country'] = df['native_country'].mask(df['native_country'] != 'United-States', 'Other')

4. 直观的loc索引赋值

通过布尔索引定位非目标值的行,直接赋值,性能优异,适合大规模数据:

df.loc[df['native_country'] != 'United-States', 'native_country'] = 'Other'

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 03:01:07