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 <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.contains.html#pandas.Series.str.contains" rel="nofollow"><code>str.contains</code></a> to mask the rows that contain 'ball' and then overwrite with the new value:</p>

<pre><code>In [71]:
df.loc[df['sport'].str.contains('ball'), 'sport'] = 'ball sport'
df

Out[71]:
    name       sport
0    Bob      tennis
1   Jane  ball sport
2  Alice  ball sport
</code></pre>

<p>To make it case-insensitive pass `case=False:</p>

<pre><code>df.loc[df['sport'].str.contains('ball', case=False), 'sport'] = 'ball sport'
</code></pre>

python pandas