I'm aiming to replace column headers in a pandas df. Particularly, I want to change the columns ending in _Item
. At the moment the start of those column headers begins with whatever string is in Group_A
or Group_B
. But these strings will change with each new dataset. So I'm hoping to replace the appropriate string values with Group A
or Group B
.
At the moment, I'm manually replacing the column headers but this doesn't work if the columns aren't ordered.
df = pd.DataFrame({
'Group_A' : ['Red','Red','Red','Red','Red','Red'],
'Group_B' : ['Blue','Blue','Blue','Blue','Blue','Blue'],
'Blue_Item' : ['2','4','6','8','10','12',],
'Red_Item' : ['1','2','3','4','5','6',],
})
df.columns = [*df.columns[:-2], 'Group_A_Item','Group_B_Item']
intended output:
df = pd.DataFrame({
'Group_A' : ['Red','Red','Red','Red','Red','Red'],
'Group_B' : ['Blue','Blue','Blue','Blue','Blue','Blue'],
'Group_B_Item' : ['2','4','6','8','10','12',],
'Group_A_Item' : ['1','2','3','4','5','6',],
})