How do I apply a regex substitution in a string column
<p>I have a data frame with a column like below</p>

<pre><code>Years in current job
&lt; 1 year
10+ years
9 years
1 year
</code></pre>

<p>I want to use regex or any other technique in python to get the result as</p>

<pre><code>Years in current job
1
10
9
1
</code></pre>

<p>I got something like this but, i guess it can be done in a better way using regex</p>

<pre><code>frame["Years in current job"] = frame["Years in current job"].str.replace(" ","")
frame["Years in current job"] = frame["Years in current job"].str.replace("&lt;","")
frame["Years in current job"] = frame["Years in current job"].str.replace("year","")
frame["Years in current job"] = frame["Years in current job"].str.replace("years","")
</code></pre>

<pre><code>import re

def extract_nums(txt):
  try:
    return int(re.search('([0-9]+)', txt).group(1))
  except:
    return -1

df['Years in current job'] = df['Years in current job'].apply(extract_nums)
</code></pre>

<p>EDIT - adding context per suggestion below</p>

<p>this could be done easily enough with string methods, but I'll throw out an approach using regex since that might be helpful for more complicated tasks.</p>

<p>re.search and parenthesis will find the digits you're looking....  group extracts the match inside the parenthesis...  and try/except will handle any problems that arise if there is no match.  then just pass that function to the pandas.Series apply() method.</p>

<p>regex search:  <a href="https://docs.python.org/2/library/re.html#regular-expression-objects" rel="nofollow">https://docs.python.org/2/library/re.html#regular-expression-objects</a></p>

<p>apply method:  <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.apply.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.apply.html</a></p>

python regex pandas