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><code>.str</code> applies to the whole Series but here you are dealing with the value inside the Series.</p>

<p>You can either do : <code>df['link'].str.contains(search)</code><br>
Or like you want  : <code>df['link'].apply(lambda x: 'Search' if search in x else 'Other')</code></p>

<p><strong>Edit</strong>  </p>

<p>More generic way:</p>

<pre><code>def my_filter(x, val, c_1, c_2):
    return c_1 if val in x else  c_2 

df['link'].apply(lambda x: my_filter(x, 'homepage', 'homepage', 'other'))
</code></pre>

python string pandas condition contains