Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas replace a character in all column names

Tags:

python

pandas

I have data frames with column names (coming from .csv files) containing ( and ) and I'd like to replace them with _.

How can I do that in place for all columns?

like image 220
Cedric H. Avatar asked Sep 28 '16 08:09

Cedric H.


People also ask

How do I change a character in a column in pandas?

We can replace characters using str. replace() method is basically replacing an existing string or character in a string with a new one. we can replace characters in strings is for the entire dataframe as well as for a particular column.

How do I replace multiple column values in pandas?

Pandas replace multiple values in column replace. By using DataFrame. replace() method we will replace multiple values with multiple new strings or text for an individual DataFrame column. This method searches the entire Pandas DataFrame and replaces every specified value.

How do I get rid of special characters in pandas?

Add df = df. astype(float) after the replace and you've got it. I'd skip inplace and just do df = df. replace('\*', '', regex=True).


1 Answers

Use str.replace:

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

Sample:

df = pd.DataFrame({'(A)':[1,2,3],                    '(B)':[4,5,6],                    'C)':[7,8,9]})  print (df)    (A)  (B)  C) 0    1    4   7 1    2    5   8 2    3    6   9  df.columns = df.columns.str.replace(r"[()]", "_") print (df)    _A_  _B_  C_ 0    1    4   7 1    2    5   8 2    3    6   9 
like image 185
jezrael Avatar answered Sep 18 '22 08:09

jezrael