title: Pandas removing whitespace in part of string
body: <p>I am writing a regex code to remove the whitespace for financial values of the string in pandas dataframe. Let's suppose a pandas dataframe called df and a column "detail" is in the dataframe df.</p>
  
  <p>For example, the column contains string like: </p>
  
  <p>"maximum USD 1 000 000 per house as respects Detroit"</p>
  
  <p>"minimum $ 3 000 000 per destroyed house due to Earthquake"</p>
  
  <p>I tried using str.replace method in pandas, with regex applied. However,</p>
  
  <pre><code>df['detail'].str.replace(r"(USD)\s*(\d+\s*)+(\d+)", r"USD\s\d+\d+", regex=True)
  
  df['detail'].str.replace(r"(\$)\s*(\d+\s*)+(\d+)", r"\$\s\d+\d+", regex=True)
  </code></pre>
  
  <p>will return </p>
  
  <p>"maximum USD\s\d+\d+ per house as respects Detroit" </p>
  
  <p>"minimum \$\s\d+\d+ per destroyed house due to Earthquake"
  rather than replacing the number with the right format.</p>
  
  <p>The expected result is to remove the whitespace for financial values and return:</p>
  
  <p>"maximum USD 1000000 per house as respects Detroit"</p>
  
  <p>"minimum $ 3000000 per destroyed house due to Earthquake"</p>
  
  <p>What code should I try to remove whitespace inside the financial values? The actual data is huge so manual work is going to be immense.</p>
  
  <p><strong>Solved:</strong></p>
  
  <p>Thanks for the answers, I used the following code and it works well. In big data it is possible for the USD/$ to have multiple whitespaces before the financial number (Or it could be 0), so \s+ or \s* provide a safe approach for this problem.</p>
  
  <pre><code>df['detail'] = df['detail'].apply(lambda x: re.sub(r'\s+(\d{3})', r'\1', x))
  </code></pre>