Newboi
Newboi

Reputation: 1

Is there a way to find and replace any character in a column in pandas dataframe?

So, I am struggling a bit in pandas. How do I find and replace any character in a particular column of a dataframe?

For Example, in the below dataframe:

1. If I want to replace any parentheses with a '-' in column x of the dataframe below or a number in column 'y' with a '-'.

2. Another question I have is how to replace everything within the () in column 'x' .
ie. ('There') is replaced with '-'.

df=pd.DataFrame(data=({'x':['Hello','(There)'],'y':['R17','R16']}))

I would be really grateful if someone could help me tell me the code for this and how it works.

Upvotes: 0

Views: 72

Answers (1)

Danail Petrov
Danail Petrov

Reputation: 1875

Not sure if this is what you're looking for, but here is some example:

patern = r'\(|\)|\d+'
df.replace(patern, '-', regex=True)

will output

>         
x   y
0    Hello  R-
1  -There-  R-

Upvotes: 0

Related Questions