Use str.replace:
df.columns = df.columns.str.replace("[()]", "_", regex=True)
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"[()]", "_", regex=True)
print (df)
_A_ _B_ C_
0 1 4 7
1 2 5 8
2 3 6 9
Answer from jezrael on Stack OverflowUse str.replace:
df.columns = df.columns.str.replace("[()]", "_", regex=True)
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"[()]", "_", regex=True)
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)]
python - Replace string in pandas df column name - Stack Overflow
How to replace column names with Pandas?
python - Replace column names in a pandas data frame that partially match a string - Stack Overflow
Working With Missing And Duplicate Data - str.replace() problem
I'm working on a very large dataset (from an Excel document) that has the price information of 415 different products for each month since January 2003. For example, when you open the Excel document the first six months look like below.
2003 2003 2003 2003 2003 2003
January February March April May June
When I used the read_excel() method with the header parameter as follows df.read_excel(header=5), the months in 2004 are read as January.1, February.1 etc. Similarly headers for 2005 look like January.2, February.2 and so on.
When I was using a small portion of the data I just created a dictionary for the old headers as keys and new headers as values and used products.rename(columns=dict_name) but now I want to work on the whole document, which has more than 200 headers but I don't want to rename them individually.
I was wondering if there is an easy way to rename all headers with something like find and replace all that includes ".1" for 2004 for example. so that they reflect their respective years along with the months.
I tried to explain the best I could and hope I could explain what I have in my mind.
does this work ?
df.columns = [col + ' = ' + str(newElements.pop(0)) if col.startswith(stringMatch) else col for col in df.columns]
You can use a list comprehension :
df.columns = [ i if "_" not in i else i + "=" + str(newElements[int(i[-1])-1]) for i in df.columns]
output
Price obs_1=5 obs_2=10 obs_3=15 obs_4=20
0 103 92 92 96 107
1 109 100 91 90 107
2 105 99 90 104 90
3 105 109 104 94 90
4 106 94 107 93 92