Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace multiple characters across all columns pandas df

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 ()

like image 728
Chique_Code Avatar asked Mar 11 '26 17:03

Chique_Code


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 _.

like image 166
Wiktor Stribiżew Avatar answered Mar 13 '26 07:03

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!