Replace whole string if it contains substring in pandas
<p>Im sorry if this is a very obvious and easy question but I've been searching the internet for a solution but couldn't come up with one that works (and I don't really have much knowledge in python). I want to replace all strings that contain a specific substring. So for example if I have this dataframe:</p>

<pre><code>import pandas as pd
df = pd.DataFrame({'name': ['Bob', 'Jane', 'Alice'], 
               'sport': ['tennis', 'football', 'basketball']})
</code></pre>

<p>I could replace football with the string 'ball sport' like this:</p>

<pre><code>df.replace({'sport': {'football': 'ball sport'}})
</code></pre>

<p>What I want though is to replace everything that contains ball (in this case football and basketball) with 'ball sport'. Something like this:</p>

<pre><code>df.replace({'sport': {'[strings that contain ball]': 'ball sport'}})
</code></pre>

<p>you can use <code>str.replace</code></p>

<pre><code>df.sport.str.replace(r'(^.*ball.*$)', 'ball sport')

0        tennis
1    ball sport
2    ball sport
Name: sport, dtype: object
</code></pre>

<p>reassign with</p>

<pre><code>df['sport'] = df.sport.str.replace(r'(^.*ball.*$)', 'ball sport')
df
</code></pre>

<p><a href="http://i.stack.imgur.com/5tJgT.png" rel="nofollow"><img src="http://i.stack.imgur.com/5tJgT.png" alt="enter image description here"></a></p>

python pandas