Reputation: 1530
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 ()
Upvotes: 3
Views: 2497
Reputation: 627087
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 _
.
Upvotes: 9