Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace only a few headers in dataframe from list

I have a dataframe that I want to change the last 30 headers of. I have a list of the values that need to be changed, but I want to keep the original first two headers from the dataframe. For example, my dataframe resembles

Customer ID     Email     Topwater    ...    Plastics    Finesse
12345           [email protected] 1           ...    1           0
...

and my list is:

[Bait #1, Bait #2, Bait #3, ... , Bait #10, Bait #11]

I'm looking achieve this:

Customer ID     Email     Bait#1    ...    Bait #10    Bait #11
12345           [email protected] 1         ...    1           0
...

I tried this (where df_binary is the dataframe with the headers I want to change, but it doesn't seem to do anything, just returns the initial dataframe:

header_list = ['Customer ID','Email']
header_list.extend(list_of_baits)
df_binary.iloc[:,2:37].columns = my_list2
like image 208
beflyguy Avatar asked Feb 17 '26 22:02

beflyguy


2 Answers

I think need for replace last 3 values - convert all columns names without last to list and add new items:

print (df)
   Customer         ID  Email Topwater  ...  Plastics  Finesse
0     12345  [email protected]      1      ...    1         0        4

list_of_baits = ['Bait #1','Bait #2','Bait #3']
#for last 30 change -3 to -30
df.columns = df.columns[:-3].tolist() + list_of_baits
print (df)
   Customer         ID  Email Topwater  Bait #1  Bait #2  Bait #3
0     12345  [email protected]      1      ...        1        0        4
like image 192
jezrael Avatar answered Feb 21 '26 15:02

jezrael


Data from jpp rename

df= df.rename(columns=dict(zip(df.columns[-3:],list_of_baits)))
#df.rename(columns=dict(zip(df.columns.values[-3:],list_of_baits)))
Out[238]: 
Empty DataFrame
Columns: [Customer ID, Email, Bait #1, Bait #2, Bait #3]
Index: []
like image 22
BENY Avatar answered Feb 21 '26 15:02

BENY