仅替换列表中数据框中的几个标题

时间:2018-07-16 13:39:47

标签: python pandas dataframe

我有一个要更改其最后30个标头的数据框。我有一个需要更改的值的列表,但我想保留数据帧中原始的前两个标头。例如,我的数据框类似于

Customer ID     Email     Topwater    ...    Plastics    Finesse
12345           me@me.com 1           ...    1           0
...

我的名单是:

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

我正在寻求实现:

Customer ID     Email     Bait#1    ...    Bait #10    Bait #11
12345           me@me.com 1         ...    1           0
...

我尝试了此操作(其中df_binary是要更改标题的数据帧,但似乎没有任何作用,只是返回了初始数据帧:

header_list = ['Customer ID','Email']
header_list.extend(list_of_baits)
df_binary.iloc[:,2:37].columns = my_list2

3 个答案:

答案 0 :(得分:2)

我认为需要替换最后3个值-将所有列名(不包含最后一个)转换为list并添加新项目:

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

答案 1 :(得分:2)

您可以检索数据框列下方的数组,并更新最后的 n 项:

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')

请注意,您不应尝试直接更新df.columns,因为Pandas索引对象不支持可变操作。您也不应尝试直接更新df.columns.values,因为这可能会带来意想不到的副作用。

答案 2 :(得分:2)

来自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: []
相关问题