Home > Mobile >  How to replace parentheses from a string in pandas dataframe
How to replace parentheses from a string in pandas dataframe

Time:11-19

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)

CodePudding user response:

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
  • Related