Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Dollar Sign from Entire Python Pandas Dataframe

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.

like image 467
d84_n1nj4 Avatar asked Mar 29 '17 14:03

d84_n1nj4


People also ask

How do I remove the dollar sign from a DataFrame in Python?

First of all, create a data frame. Then, use gsub function along with lapply function to remove dollar sign.

How do I remove the dollar sign from a data frame?

Dollar signs can also be removed from a dataframe column or row, by using the gsub() method. All the instances of the $ sign are removed from the entries contained within the data frame.

How do I remove special characters from a DataFrame in Python?

Add df = df. astype(float) after the replace and you've got it. I'd skip inplace and just do df = df. replace('\*', '', regex=True).

How do I get rid of the sign in Python?

You can use str. strip() to remove the whitespaces around the string, and str. replace() to replace the $ with a empty character.


1 Answers

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
like image 112
jezrael Avatar answered Sep 21 '22 01:09

jezrael