-1

Let's say I have the following df:

import pandas as pd

df = pd.DataFrame({'A':['1^','2','3'],
                   'B':['1^','2','3'],
                   'C':['1^','2','3']})
df

    A   B   C
0   1^  1^  1^
1   2   2   2
2   3   3   3

I want to remove the '^' from the entire dataframe, so I thought using the .replace() method would work:

cols_to_check = ['A','B', 'C']
df[cols_to_check] = df[cols_to_check].replace({'^':''}, regex=True)

However, this is the output:

df

    A   B   C
0   1^  1^  1^
1   2   2   2
2   3   3   3

Nothing happens! This works with any character other than the carat symbol and it's frustrating me. Here is an example:

df[cols_to_check] = df[cols_to_check].replace({'2':''}, regex=True)
df


    A   B   C
0   1^  1^  1^
1           
2   3   3   3

Why is the carat symbol so stubborn? Is there a way I can fix this? It would be really helpful. Thanks!

bismo
  • 1,257
  • 1
  • 16
  • 36

1 Answers1

2

Special character add \

df=df.replace({'\^':''}, regex=True)
   A  B  C
0  1  1  1
1  2  2  2
2  3  3  3
BENY
  • 317,841
  • 20
  • 164
  • 234