Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

regex - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...