1

Lets say i have a dataframe like this:

       Col1
0     Test1_2345)
1     Test2_(123
2     Test3_567)_rt
3     Test5_874)

How can I replace "(" and ")" from the strings in Col1 and have a dataframe like this:

       Col1
0     Test1_2345
1     Test2_123
2     Test3_567_rt
3     Test5_874

I tried this one but it is not working:

df['Col1'] = df['Col1'].replace("(","",regex=True)
df['Col1'] = df['Col1'].replace(")","",regex=True)
user14073111
  • 647
  • 5
  • 14
  • Does this answer your question? [How to replace text in a column of a Pandas dataframe?](https://stackoverflow.com/questions/28986489/how-to-replace-text-in-a-column-of-a-pandas-dataframe) – Mahrkeenerh Nov 18 '21 at 21:33
  • 3
    parenthesis are actual tokens in regex, you need to escape them if you literally mean a parenthesis. `df.Col1.str.replace('\(|\)','')` In this case, left OR right – Chris Nov 18 '21 at 21:34
  • 1
    Can also do a character class without escaping `df['Col1'] = df['Col1'].replace('[()]', '', regex=True)` – Henry Ecker Nov 18 '21 at 21:41
  • Thanks a lot @Chris and henryecker, also this is working – user14073111 Nov 18 '21 at 21:45

1 Answers1

3

Replace everything other than \w . \w Matches alphanumeric characters and the underscore, _.

df1['Col1'] = df1['Col1'].str.replace('[^\w]','', regex=True)

0      Test1_2345
1       Test2_123
2    Test3_567_rt
3       Test5_874
wwnde
  • 26,119
  • 6
  • 18
  • 32