python Pandas : Filter Dataframe by applying regular expression

标签 python regex pandas

我可以像这样根据列表的元素过滤数据框;

import pandas as pd
W1 = ['Animal','Ball','Cat','Derry','Element','Lapse','Animate this']
W2 = ['Krota','Catch','Yankee','Global','Zeb','Rat','Try']
df = pd.DataFrame({'W1':W1,'W2':W2})

l1 = ['Animal','Zeb','Q']
print df[df['W1'].isin(l1) | df['W2'].isin(l1)]

        W1     W2
  0   Animal  Krota
  4  Element    Zeb

但是有没有办法通过应用正则表达式进行过滤? 例如;

 l1 = ['An','Cat']

 Intended result;
          W1         W2
  0   Animal        Krota
  1   Ball          Catch  
  2   Cat           Yankee
  6   Animate this  Try 

最佳答案

试试这个:

df[df['W1'].str.contains("|".join(l1)) | df['W2'].str.contains("|".join(l1))]


             W1      W2
0        Animal   Krota
1          Ball   Catch
2           Cat  Yankee
6  Animate this     Try

关于 python Pandas : Filter Dataframe by applying regular expression,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22093006/

相关文章:

Python:嵌套函数外部作用域中的引用变量(非全局)

regex - 在 Perl 中使用正则表达式有效匹配一组文件名

regex - 需要 Linux 中文件每一行的最后一个完整单词

python - 如何将分钟添加到 datetime.time。 python / Pandas

python - 如何从 GroupBy.apply() 中删除多索引?

python - 复制带有 Telethon 的帖子链接

python - 在没有exec/eval,python的字符串中调用代码

python - pandas groupby 和 reset_index 如何更改数据框的索引?

Python 正则表达式子

python - 涉及 ?q= 搜索查询的 URL 的 Django 正则表达式模式不起作用