我在可能包含键的列中有一个搜索列表:'keyword1*keyword2'
尝试在单独的数据框列中查找匹配项。如何包含正则表达式通配符类型'keyword1.*keyword2'
#using str.extract, extractall or findall?
使用.str.extract
可以很好地匹配精确子字符串,但我还需要它来匹配关键字之间带有通配符的子字符串。
# dataframe column or series list as keys to search for:
dfKeys = pd.DataFrame()
dfKeys['SearchFor'] = ['this', 'Something', 'Second', 'Keyword1.*Keyword2', 'Stuff', 'One' ]
# col_next_to_SearchFor_col
dfKeys['AdjacentCol'] = ['this other string', 'SomeString Else', 'Second String Player', 'Keyword1 Keyword2', 'More String Stuff', 'One More String Example' ]
# dataframe column to search in:
df1['Description'] = ['Something Here','Second Item 7', 'Something There', 'strng KEYWORD1 moreJARGON 06/0 010 KEYWORD2 andMORE b4END', 'Second Item 7', 'Even More Stuff']]
# I've tried:
df1['Matched'] = df1['Description'].str.extract('(%s)' % '|'.join(key['searchFor']), flags=re.IGNORECASE, expand=False)
我也尝试用 'extractall' 和 'findall' 替换上面代码中的 'extract',但它仍然没有给我我需要的结果。我希望'Keyword1*Keyword2'
匹配"strng KEYWORD1 moreJARGON 06/0 010 KEYWORD2 andMORE b4END"
更新:'.*' 有效!我还尝试将单元格中的值添加到 'SearchFor' 列中匹配的键旁边,即dfKeys['AdjacentCol']
.
我试过:df1['From_AdjacentCol'] = df1['Description'].str.extract('(%s)' % '|'.join(key['searchFor']), flags=re.IGNORECASE, expand=False).map(dfKeys.set_index('SearchFor')['AdjacentCol'].to_dict()).fillna('')
它适用于除带通配符的键之外的所有内容。
# expected:
Description Matched From_AdjacentCol
0 'Something Here' 'Something' 'this other string'
1 'Second Item 7' 'Second' 'Second String Player'
2 'Something There' 'Something' 'this other string'
3 'strng KEYWORD1 moreJARGON 06/0 010 KEYWORD2...' 'Keyword1*Keyword2' 'Keyword1 Keyword2'
4 'Second Item 7' 'Second' 'Second String Player'
5 'Even More Stuff' 'Stuff' 'More String Stuff'
非常感谢您对此的任何帮助。谢谢!
您已接近解决方案,只需更改*
为.*
. 阅读文档:
. (点。)在默认模式下,这匹配除换行符之外的任何字符。如果指定了 DOTALL 标志,则它匹配包括换行符在内的任何字符。
* 使生成的 RE 匹配前面 RE 的 0 次或多次重复,尽可能多的重复。ab* 将匹配 'a'、'ab' 或 'a' 后跟任意数量的 'b'。
在正则表达式中,星号*
本身没有任何意义。它*
与 Unix/Windows 文件系统中通常的 glob 运算符具有不同的含义。
星号是一个量词(即灰色量词),它必须与某种模式(这里.
匹配任何字符)相关联才能表示某些东西。
重塑您的 MCVE:
import re
import pandas as pd
keys = ['this', 'Something', 'Second', 'Keyword1.*Keyword2', 'Stuff', 'One' ]
df1 = pd.DataFrame()
df1['Description'] = ['Something Here','Second Item 7', 'Something There',
'strng KEYWORD1 moreJARGON 06/0 010 KEYWORD2 andMORE b4END',
'Second Item 7', 'Even More Stuff']
regstr = '(%s)' % '|'.join(keys)
df1['Matched'] = df1['Description'].str.extract(regstr, flags=re.IGNORECASE, expand=False)
正则表达式现在是:
(this|Something|Second|Keyword1.*Keyword2|Stuff|One)
并匹配缺失的情况:
Description Matched
0 Something Here Something
1 Second Item 7 Second
2 Something There Something
3 strng KEYWORD1 moreJARGON 06/0 010 KEYWORD2 an... KEYWORD1 moreJARGON 06/0 010 KEYWORD2
4 Second Item 7 Second
5 Even More Stuff Stuff
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句