我在可能包含一个键的列中有一个搜索列表:'keyword1*keyword2'
尝试在单独的数据框列中找到匹配项。如何包含正则表达式通配符类型'keyword1.*keyword2'
#using str.extract, extractall or findall?
Using.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'
对此的任何帮助都非常感谢。谢谢!