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

标签 python pandas dataframe

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

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

我的 list 是:

[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 的数据帧,但它似乎没有做任何事情,只是返回初始数据帧:

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

最佳答案

我认为需要替换最后 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

关于python - 从列表中仅替换数据框中的几个标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51363230/

相关文章:

python - 通过调换两列并重复另一列来 reshape pandas DataFrame

python - 通过python将PDF文件发布到SOLR

python - 打印带索引的 Pandas 数据框

java - 使用 shell 命令传递 Python/JAVA/Perl 选项

python - Pandas : Replace string column values

r - 将个体列表转换为 R 中对的出现

python - 每个ID创建n行| Pandas

r - 在R中找到两个数据帧之间的公共(public)ID

python - 如何使用 solve_ivp 通过精确点?

python - 安装 Python 2.7 和 Python 3.5 后,使用 IDLE 编辑选项不可用。应该做什么?