Filtering DataFrames in Pandas for multiple columns where a column name contains a pattern
<p>While filtering multiple columns I have seen examples where we could filter Rows using something like this <code>df[df['A'].str.contains("string") | df['B'].str.contains("string")]</code> .</p>

<p>I have multiple files where I want to fetch each file and get only those rows with <code>'gmail.com'</code> from the column names having <code>'email'</code> string in them.  </p>

<p>So an example header can be like: 'firstname' 'lastname' 'companyname' 'address' 'emailid1' 'emailid2' 'emailid3' ...</p>

<p>The columns <code>emailid1..2..3</code> have emailids containing <code>gmail.com</code>. I would want to fetch rows where gmail can occur in any one of them.</p>

<pre><code>for file in files:
    pdf = pd.read_csv('Reduced/'+file,delimiter = '\t')
    emailids = [col for col in pdf.columns if 'email' in col]
    #  pdf['gmail' in pdf[emailids]]
</code></pre>

<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.any.html" rel="nofollow"><code>any</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a>:</p>

<pre><code>pdf = pd.DataFrame({'A':[1,2,3],
                   'email1':['gmail.com','t','f'],
                   'email2':['u','gmail.com','t'],
                   'D':[1,3,5],
                   'E':[5,3,6],
                   'F':[7,4,3]})
print (pdf)
   A  D  E  F     email1     email2
0  1  1  5  7  gmail.com          u
1  2  3  3  4          t  gmail.com
2  3  5  6  3          f          t

#filter column names                   
emailids = [col for col in pdf.columns if 'email' in col]
print (emailids)
['email1', 'email2']

#apply string function for each filtered column
df = pd.concat([pdf[col].str.contains('gmail.com') for col in pdf[emailids]], axis=1)

print (df)
  email1 email2
0   True  False
1  False   True
2  False  False

#filter at least one True by any
print (pdf[df.any(1)])
   A  D  E  F     email1     email2
0  1  1  5  7  gmail.com          u
1  2  3  3  4          t  gmail.com
</code></pre>

python pandas indexing filter multiple-columns