How to partially remove content from cell in a dataframe using Python
<p>I have the following dataframe:</p>

<pre><code>import pandas as pd    
df = pd.DataFrame([
        ['\nSOVAT\n', 'DVR', 'MEA', '\n195\n'],
        ['PINCO\nGALLO ', 'DVR', 'MEA\n', '195'],
    ])
</code></pre>

<p>which looks like this:</p>

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

<p>My goal is to analyze every single cell of the dataframe so that:</p>

<ul>
<li>if the substring <code>\n</code> appears only once, then I delete it along with all the characters that come before it;</li>
<li>if the substring <code>\n</code> appears more than once in a specific cell, then I remove all the <code>\n</code> contained along with what comes before and after them (except for what is in between)</li>
</ul>

<p>The output of the code should be this:</p>

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

<p>Notice: so far I only know how to remove the what comes before or after the substring by using the following command:</p>

<pre><code>df = df.astype(str).stack().str.split('\n').str[-1].unstack() 
df = df.astype(str).stack().str.split('\n').str[0].unstack() 
</code></pre>

<p>However this line of code does not lead me to the desired results since the output is:</p>

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

<p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html" rel="nofollow"><code>df.replace</code></a> and some regex.</p>

<pre><code>In [1]: import pandas as pd
   ...: df = pd.DataFrame([
   ...:         ['\nSOVAT\n', 'DVR', 'MEA', '\n195\n'],
   ...:         ['PINCO\nGALLO ', 'DVR', 'MEA\n', '195'],
   ...:     ])
   ...:

In [2]: df.replace(r'.*\n(.*)\n?.*', r'\1', regex=True)
Out[3]:
        0    1    2    3
0   SOVAT  DVR  MEA  195
1  GALLO   DVR       195
</code></pre>

python pandas dataframe removing-whitespace