10

I'm looking to remove dollar signs from an entire python pandas dataframe. It's similar to this post:

Remove Entire Character

However, I'm looking to remove the dollar sign which is not working. I believe it's because regex sees the dollar sign as the end of the string, but I'm not sure what to do about it. Here is what I have created so far:

dftest = pd.DataFrame({'A':[1,2,3],
                       'B':[4,5,6],
                       'C':['f;','$d:','sda%;sd$'],
                       'D':['s%','d;','d;p$'],
                       'E':[5,3,6],
                       'F':[7,4,3]})

Which gives the output:

In [155]: dftest
Out[155]:
   A  B         C     D  E  F
0  1  4        f;    s%  5  7
1  2  5       $d:    d;  3  4
2  3  6  sda%;sd$  d;p$  6  3

I then try to remove the dollar signs as follows:

colstocheck = dftest.columns

dftest[colstocheck] = dftest[colstocheck].replace({'$':''}, regex = True)

That does not remove the dollar signs but this code does remove the percent signs:

dftest[colstocheck] = dftest[colstocheck].replace({'%':''}, regex = True)

So I'm not sure how to replace the dollar signs.

Community
  • 1
  • 1
d84_n1nj4
  • 1,712
  • 6
  • 23
  • 40

2 Answers2

22

You need escape $ by \:

dftest[colstocheck] = dftest[colstocheck].replace({'\$':''}, regex = True)
print (dftest)
   A  B        C    D  E  F
0  1  4       f;   s%  5  7
1  2  5       d:   d;  3  4
2  3  6  sda%;sd  d;p  6  3
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • Ahh, I was playing around with that but couldn't get it to work--I'm not familiar with regex. Thanks! – d84_n1nj4 Mar 29 '17 at 14:34
  • 2
    Note: you can specify numerous characters in the `dict` as well: `{'\$': '', ',': ''}` to replace dollar signs and commas, for example. Super handy when dealing with garbage Excel exports :) – Hendy Sep 26 '17 at 15:50
1

To add to jezrael's answer. add 'r' before the backslash string to avoid pep8 invalid escape sequence warning.

dftest[colstocheck] = dftest[colstocheck].replace({r'\$':''}, regex = True)
Sam_Kim
  • 11
  • 1