richie
richie

Reputation: 18638

Python Pandas: Filter Dataframe by applying regular expression

I am able to filter a dataframe based on the elements of a list like this;

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

But is there a way to filter by applying regular expressions; For ex;

 l1 = ['An','Cat']

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

Upvotes: 2

Views: 4425

Answers (1)

Zero
Zero

Reputation: 76917

Try this:

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

Upvotes: 6

Related Questions