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

Pandas如何不区分大小写多条件匹配设置DataFrame列值

方案1:使用replace结合布尔索引实现

你可以先批量完成两类code的替换,再通过布尔匹配把剩下不满足条件的值统一设为空字符串,代码如下:

import pandas as pd

# 原始DataFrame
df = pd.DataFrame({"code": ["codeA",
                            "Codeb",
                            "codeB",
                            "codea",
                            "N/A",
                            "N/A"], 
                   "warehouse": [20, 
                                 30, 
                                 10,
                                 30,
                                 10,
                                 70]})

# 单次replace完成两类匹配替换,比多次调用replace性能更高
df['code'] = df['code'].replace({"(?i)codeA": "product A", "(?i)codeB": "product B"}, regex=True)
# 把未匹配到的取值统一设为空
df.loc[~df['code'].isin(["product A", "product B"]), 'code'] = ""

方案2:使用np.where实现完整if-elif-else逻辑

如果希望在一次计算中走完所有分支,完全对应你给出的伪代码逻辑,可以用numpy的where嵌套实现:

import numpy as np

df['code'] = np.where(df['code'].str.contains('(?i)codeA'), "product A",
                      np.where(df['code'].str.contains('(?i)codeB'), "product B",
                               ""))

方案3:映射字典+自定义函数(适合规则扩展)

如果后续需要新增更多code映射规则,用字典统一管理规则可维护性更高:

# 统一管理匹配规则,新增规则只需要修改这个字典
rule_map = {
    r'(?i)^codeA$': 'product A',
    r'(?i)^codeB$': 'product B'
}

def map_code(val):
    for pattern, res in rule_map.items():
        if pd.Series([val]).str.match(pattern).iloc[0]:
            return res
    return ""

df['code'] = df['code'].apply(map_code)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 00:39:03