首页 > 解决方案 > 数据框中的动态正则表达式

问题描述

具有如下数据框:

df= pd.DataFrame({'category':['Fishing','Refrigeration','store'],'synonyms_text':['seafood','foodlocker',' food']})

清单如下:

list_desc=['FOOD', 'GROWERS', 'INTERNATIONAL']

如何迭代list_desc以创建要在数据框中使用的动态正则表达式?

for word in list_desc:
    print(word.lower())
    df_tmp= df.loc[df['synonyms_text'].str.contains(r'\bfood\b')]

wherefood必须用word变量替换。

谢谢

标签: pythonregexpandas

解决方案


您可以使用format()like in动态构建您的正则表达式r'\b{0}\b'.format(word)

例子:

for word in list_desc:
    df_tmp= df.loc[df['synonyms_text'].str.contains(r'\b{0}\b'.format(re.escape(word.lower())))]

更多信息:如何在正则表达式中使用变量?


推荐阅读