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 ()
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 _.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With