Conditional editing of strings in a Pandas DataFrame
<p>I am learning Pandas and have a DataFrame of strings which looks a little like this:</p>

<pre><code>df = pd.DataFrame([['Apple', 'Med6g7867'], ['Orange', 'Med7g8976'], ['Banana', 'Signal'], ['Peach', 'Med8g8989'], ['Mango', 'Possible result %gggyy']], columns=['A', 'B'])
df
    A       B
0   Apple   Med6g7867
1   Orange  Med7g8976
2   Banana  Signal
3   Peach   Med8g8989
4   Mango   Possible result %gggyy
</code></pre>

<p>Note column B has two types of value, either a unique identifier of the form MedXgXXXX or a descriptive string. I would like to do two related things.</p>

<ol>
<li>Substitute all the values of B with the unique identifier to NaN</li>
<li>Retain the descriptive string but truncate any that have a % sign so that I only retain the string prior to the % sign.</li>
</ol>

<p>I would like a table like this:</p>

<pre><code>    A       B
0   Apple   NaN
1   Orange  NaN
2   Banana  Signal
3   Peach   NaN
4   Mango   Possible result
</code></pre>

<p>Currently I can subset the table like so:</p>

<pre><code>df[df['B'].str.contains("Med")]
df[df['B'].str.contains("%")]
</code></pre>

<p>but no implementation of <code>replace()</code> I try allows me to do this.</p>

<p>Any help appreciated.</p>

<p>You can apply replace twice like this:</p>

<pre><code>In [460]: df
Out[460]: 
        A                       B
0   Apple               Med6g7867
1  Orange               Med7g8976
2  Banana                  Signal
3   Peach               Med8g8989
4   Mango  Possible result %gggyy

In [461]: df.replace(r'Med\dg\d{4}', np.nan, regex=True).replace(r'\s+%.*', '', regex=True)
Out[461]: 
        A                B
0   Apple              NaN
1  Orange              NaN
2  Banana           Signal
3   Peach              NaN
4   Mango  Possible result
</code></pre>

python regex pandas