pandas keep numerical part
<p>I have a set of data like: </p>

<pre><code>        0       1 
0  type 1  type 2
1  type 3  type 4
</code></pre>

<p>How can I transfer it to:</p>

<pre><code>   0  1
0  1  2
1  3  4
</code></pre>

<p>perfer using <code>apply</code>or <code>transform</code> function</p>

<p>You can use <code>applymap</code> and a regex (<code>import re</code>):</p>

<pre><code>df = df.applymap(lambda x: re.search(r'.*(\d+)', x).group(1))
</code></pre>

<p>If you want the digits as integers:</p>

<pre><code>df = df.applymap(lambda x: int(re.search(r'.*(\d+)', x).group(1)))
</code></pre>

<p>This will work even if you have other text instead of <code>type</code>, and only with integers (ie <code>'type 1.2'</code> will break this code), so you will have to adapt it.</p>

<p>Also note that this code is bound to fail if no number is found (ie <code>'type'</code>). You may want to create a function that can handle these errors instead of the <code>lambda</code>:</p>

<pre><code>def extract_digit(x):
     try:
         return int(re.search(r'.*(\d+)', x).group(1))
     except (ValueError, AttributeError):
         # return the existing value
         return x

df = df.applymap(lambda x: extract_digit(x))
</code></pre>

python string pandas replace numeric