thenoirlatte
thenoirlatte

Reputation: 349

Error when try to replace bracket character "(" or ")" in a dataframe

I'm trying to replace character "(" and ")" in my data frame with space, but got an error:

error: unbalanced parenthesis at position 1

Here is my code:

df['ytest']=df['ytest'].str.replace("(","")
df['ytest']=df['ytest'].str.replace(")","")

Here is the example of the dataframe:

| ytest                                                       |
|=============================================================|
|('pasal xx tahun 2002',)                                     |
|('pasal 1 tahun 2009', 'pasal 2 2012', 'pasal 4', 'pasal 8') |
|('pasal 1b',)                                                |
|('pasal 16', 'pasal 9')                                      |

Upvotes: 1

Views: 303

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626927

It appears you just need to join the values:

df['ytest'] = df['ytest'].str.join(', ')

If you want another delimiter between the individual values, replace ', ' with the value you need.

If your rows contained string data, you could use

df['ytest']=df['ytest'].str.replace("[()]", "", regex=True)

Or, if you do not want to use a regex:

df['ytest']=df['ytest'].str.replace("(", "", regex=False)
df['ytest']=df['ytest'].str.replace(")", "", regex=False)

From the Pandas 1.1.5 documentation:

If you do want literal replacement of a string (equivalent to str.replace()), you can set the optional regex parameter to False, rather than escaping each character. In this case both pat and repl must be strings

Upvotes: 1

Related Questions