【发布时间】:2019-09-04 12:01:18
【问题描述】:
我在可能包含键的列中有一个搜索列表:'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'
对此的任何帮助都非常感谢。谢谢!
【问题讨论】:
-
@Wiktor Stribiżew 我没有遇到过一些类似的问题,但没有一个能解决我遇到的通配符问题。
-
您正在使用不使用通配符的
.str.extract,它使用正则表达式。匹配两个字符串之间的任何字符是一个过于频繁的正则表达式问题,因此是重复的原因。
标签: python regex pandas wildcard-expansion