Skip to content
Advertisement

Replace with Python regex in pandas column

a = "Other (please specify) (What were you trying to do on the website when you encountered ^f('l1')^?Âxa0)"

There are many values starting with ‘^f’ and ending with ‘^’ in a pandas column. And I need to replace them like below :

"Other (please specify) (What were you trying to do on the website when you encountered THIS ISSUE?Âxa0)"

Advertisement

Answer

You don’t mention what you’ve tried already, nor what the rest of your DataFrame looks like but here is a minimal example:

# Create a DataFrame with a single data point
df = pd.DataFrame(["... encountered ^f('l1')^?Âxa0)"])

# Define a regex pattern
pattern = r'(^f.+^)'

# Use the .replace() method to replace
df = df.replace(to_replace=pattern, value='TEST', regex=True)

Output

                          0
0  ... encountered TEST? )
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement