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

Pandas DataFrame字符串精确匹配:如何避免部分匹配?

Pandas字符串精确匹配解决方案

要实现完全精确匹配(仅匹配值为'tree'、'bush'或'forest'的行,而非包含这些子串的行),直接使用isin()方法即可,这是Pandas中处理此类需求最简洁高效的方式。

修改后的代码

import pandas as pd
import numpy as np

data = {'A':['tree','bush','forest','tree/red']}
df_test = pd.DataFrame(data)

# 用isin()做精确匹配判断
df_test['New'] = np.where(df_test['A'].isin(['tree', 'bush', 'forest']), 'Good', '')

原方法失效原因

你之前使用的str.contains(),即便设置regex=False,其核心逻辑仍是检查字符串中是否包含指定子串,而非判断字符串是否完全相等,所以'tree/red'因包含'tree'子串会被误匹配。

备选方案(匹配项较少时可用)

如果需要匹配的元素数量不多,也可以直接用等于判断结合逻辑或,但这种方式在匹配项增多时会显得冗长:

df_test['New'] = np.where(
    (df_test['A'] == 'tree') | 
    (df_test['A'] == 'bush') | 
    (df_test['A'] == 'forest'), 
    'Good', ''
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 14:02:03