Pandas and apply function to match a string
<p>I have a df column containing various links, some of them containing the string <code>"search"</code>.</p>

<p>I want to create a function that - being applied to the column - returns a column containing <code>"search"</code> or <code>"other"</code>.</p>

<p>I write a function like:</p>

<pre><code>search = 'search'
def page_type(x):
if x.str.contains(search):
    return 'Search'
else:
    return 'Other'   

df['link'].apply(page_type)
</code></pre>

<p>but it gives me an error like:</p>

<blockquote>
  <p>AttributeError: 'unicode' object has no attribute 'str'</p>
</blockquote>

<p>I guess I'm missing something when calling the str.contains().</p>

<p>You can use also a <code>list comprehesion</code> if you want to find the word search within a link:</p>

<p>Fo example:</p>

<pre><code>df['Search'] = [('search' if 'search' in item else 'other') for item in df['link']]
</code></pre>

<p>The output:</p>

<pre><code>  ColumnA                       link  Search
0       a        http://word/12/word   other
1       b     https://search-125.php  search
2       c      http://news-8282.html   other
3       d http://search-hello-1.html  search
</code></pre>

<p>Create function:</p>

<pre><code>def page_type(x, y):
    df[x] = [('search' if 'search' in item else 'other') for item in df[y]]

page_type('Search', 'link')

In [6]: df
Out[6]:
  ColumnA                        link  Search
0       a         http://word/12/word   other
1       b      https://search-125.php  search
2       c       http://news-8282.html   other
3       d  http://search-hello-1.html  search 
</code></pre>

python string pandas condition contains