简体   繁体   中英

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           me@me.com 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           me@me.com 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

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  me@me.com      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  me@me.com      1      ...        1        0        4

You can retrieve the array underlying your dataframe columns and update the last n items:

list_of_baits = ['Bait #1', 'Bait #2', 'Bait #3']

df = pd.DataFrame(columns=['Customer ID', 'Email', 1, 2, 3])

arr = df.columns.values
arr[-3:] = list_of_baits  # change -3 to -30
df.columns = arr

print(df.columns)

Index(['Customer ID', 'Email', 'Bait #1', 'Bait #2', 'Bait #3'], dtype='object')

Note you should not attempt to update df.columns directly, since Pandas index objects do not support mutable operations. Nor should you attempt to update df.columns.values directly, as this may have unintended side-effects.

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: []

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM