首页 > 解决方案 > 如何根据字符串列表在 df col 中查找字符串匹配?

问题描述

我有一份 1000 家公司的名单,以及当年所有以前交易的 df。对于每场比赛,我想在新列 (df$Covered) 中创建一个新行值 (True)。

我不确定为什么我不断收到以下错误。我尝试研究这些问题,但到目前为止还没有运气。

将字符串匹配到已定义字符串的列表

Pandas 从 df 中提取行,其中 df['col'] 值与 df2['col'] 值匹配

代码示例:当我设置 regex=False

Customer_List = ['3M','Cargill,'Chili's,---]

df['Covered'] = df[df['End Customer Name'].str.contains('|'.join(Customer_List),case=False, na=False, regex=False)]

ValueError:错误的项目数通过 32,位置意味着 1

代码示例:当我设置 regex=True

错误:位置 177825 处的错误字符范围 HD

 ~/opt/anaconda3/lib/python3.7/sre_parse.py in parse(str, flags, pattern)
    928 
    929     try:
--> 930         p = _parse_sub(source, pattern, flags & SRE_FLAG_VERBOSE, 0)
    931     except Verbose:
    932         **# the VERBOSE flag was switched on inside the pattern.  to be**

~/opt/anaconda3/lib/python3.7/sre_parse.py in _parse_sub(source, state, verbose, nested)
    424     while True:
    425         itemsappend(_parse(source, state, verbose, nested + 1,
--> 426                            **not nested and not items**))
    427         if not sourcematch("|"):
    428             break

标签: pythonpandas

解决方案


谢谢大家,这与我的 Customer_List 有特殊字符有关,所以我需要使用 map(re.escape

此链接帮助我了解 Python 正则表达式错误字符范围。


推荐阅读