python - 查找一个系列在另一个系列中的匹配项,并使用正则表达式匹配打印整行数据帧

标签 python regex python-3.x pandas dataframe

如何从具有 3 列的数据帧的 col1 中找到第一个系列中的匹配项?我也需要能够使用正则表达式,因为我的系列包含 * 作为该字段中任何内容的占位符。

我有一个 pandas 系列,其中包含如下数据:

col1
joe\creed\found\match
matt\creed\*\not
adam\creed\notfound\match

我有另一个数据框,其数据如下:

col1                       col2 col3
joe2\creed2\found\match    2    23
matt2\creed2\found2\not    2    23
adam\creed\notfound\match  2    23
matt\creed\found\not       2    23

我尝试执行以下代码但没有成功。

for item in series:
    print(df[df.col1.str.contains(item, regex=True)]

for item in series:
    print(df[df.col1.isin([str(item)])

我的预期输出如下:

col1                       col2 col3
adam\creed\notfound\match  2    23
matt\creed\found\not       2    23

最佳答案

你可以这样做:

数据:

In [163]: s
Out[163]:
0        joe\creed\found\match
1             matt\creed\*\not
2    adam\creed\notfound\match
Name: col1, dtype: object

In [164]: df
Out[164]:
                        col1  col2  col3
0    joe2\creed2\found\match     2    23
1    matt2\creed2\found2\not     2    23
2  adam\creed\notfound\match     2    23
3       matt\creed\found\not     2    23

解决方案:

import re

# replacing '*' --> '[^\\]*' (in the escaped string: '\\\*' --> '[^\\\\]*')
pat = s.apply(re.escape).str.replace(r'\\\*', r'[^\\\\]*').str.cat(sep='|')
# use the following line instead, if `s` is a DataFrame (not a Series):
#pat = s.col1.apply(re.escape).str.replace(r'\\\*', r'[^\\\\]*').str.cat(sep='|')


In [161]: df[df.col1.str.contains(pat)]
Out[161]:
                        col1  col2  col3
2  adam\creed\notfound\match     2    23
3       matt\creed\found\not     2    23

In [162]: pat
Out[162]: 'joe\\\\creed\\\\found\\\\match|matt\\\\creed\\\\[^\\\\]*\\\\not|adam\\\\creed\\\\notfound\\\\match'

主要困难是正确转义“搜索模式”系列中的所有特殊字符(例如 \)。

关于python - 查找一个系列在另一个系列中的匹配项,并使用正则表达式匹配打印整行数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42613051/

相关文章:

python - 迭代 Tensorflow 中的张量维度

python - 当单词以 "|"(PSV) 分隔时如何读取文件?

python - 将 emacs 缓冲区发送到任意 Python 进程

python - 使用 Python 压缩文件夹列表

python - 从 numpy 数组中检测高值

java - 替换所有抛出 PatternSyntaxException 的方法

c++ - 将字符串与 regEx 通配符值进行比较

regex - VBA积极的前瞻性太贪婪

python - 条形图中的重叠名称

python-3.x - sanic.异常.RequestTimeout : Request Timeout in Sanic