【问题标题】:Find String Pattern Match in Pandas Dataframe and Return Matched Strin在 Pandas 数据框中查找字符串模式匹配并返回匹配的字符串
【发布时间】:2014-05-07 08:43:47
【问题描述】:

我有一个带有可变逗号分隔文本的数据框列,只是试图提取基于另一个列表找到的值。所以我的数据框看起来像这样:

col1 | col2
-----------
 x   | a,b


listformatch = [c,d,f,b]
pattern = '|'.join(listformatch)

def test_for_pattern(x):
    if re.search(pattern, x):
        return pattern
    else:
        return x

#also can use col2.str.contains(pattern) for same results

上面的过滤效果很好,但不是在找到匹配项时返回b,而是返回整个模式,例如a|b,而不仅仅是b,而我想用它找到的模式创建另一列,例如b

这是我的最终函数,但仍然得到 UserWarning: This pattern has match groups. To actually get the groups, use str.extract." groups, use str.extract.", UserWarning) 我希望我能解决:

def matching_func(file1, file2):
    file1 = pd.read_csv(fin)
    file2 = pd.read_excel(fin1, 0, skiprows=1)
    pattern = '|'.join(file1[col1].tolist())
    file2['new_col'] = file2[col1].map(lambda x: re.search(pattern, x).group()\
                                             if re.search(pattern, x) else None)

我想我现在了解 pandas extract 的工作原理,但在正则表达式上可能仍然生疏。如何创建用于以下示例的模式变量:

df[col1].str.extract('(word1|word2)')

我想创建变量为pattern = 'word1|word2',而不是在参数中包含单词,但由于创建字符串的方式,这将不起作用。

我在 pandas 0.13 中使用矢量化字符串方法的最终和首选版本:

使用一列中的值从第二列中提取:

df[col1].str.extract('({})'.format('|'.join(df[col2]))

【问题讨论】:

  • 改用re.search(pattern, x).group(0)

标签: python pandas


【解决方案1】:

您可能想使用提取,或其他 vectorised string methods 之一:

In [11]: s = pd.Series(['a', 'a,b'])

In [12]: s.str.extract('([cdfb])')
Out[12]:
0    NaN
1      b
dtype: object

【讨论】:

  • 提取物似乎很棒。如果我从另一个数据框列获取字符串匹配,我将如何使用它。换句话说,对于我上面的函数,我做了'|'.join(df[col1].tolist()) 来获取我的模式。
  • 知道如何从我的程序中删除此消息:UserWarning: This pattern has match groups. To actually get the groups, use str.extract." groups, use str.extract.", UserWarning)
  • @prometheus2305 是的,在您要查找的内容周围加上括号(如我的示例所示):)
  • @prometheus2305 DataFrame 列只是一个系列,所以你可以这样做df[col1].str.extract('([cdfb])')
  • @prometheus2305 我想你在找'(%s)' % '|'.join(patterns)patterns = ['word1', 'word2']
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-09-03
  • 1970-01-01
  • 2020-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多