Replace multiple characters across all columns pandas df

Viewed 1073

My df has 200+ columns. Some of the column names contain special characters like: () [] I need to replace all 3 with _. I also need to replace empty spaces as well... Here is my code:

import pandas as pd

df = pd.read_csv('./pred_results.csv') 

df.columns = df.columns.str.replace(r"[()]", "_")

With the above code I was only able to replace ()

1 Answers

You can use

df.columns = df.columns.str.replace(r"[][() ]", "_", regex=True) 
df.columns = df.columns.str.replace(r"[][() ]+", "_", regex=True)

The first line will replace each separate ], [, (, ) and space with a _.

The second line will replace a chunk of subsequent ], [, (, ) and space chars with a single _.

Related