Pandas replace a character in all column names
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?
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
Older pandas versions don't work with the accepted answer above. Something like this is needed:
df.columns = [c.replace("[()]", "_") for c in list(df.columns)]