pandas 如何使用列表重命名熊猫中的列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40454042/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 02:22:17  来源:igfitidea点击:

how to rename columns in pandas using a list

pythonlistpandasrenamemultiple-columns

提问by Kevin Sun

I have a dataframe (df) that has 44 columns and I want to rename columns 2:44. I have a list (namesList) of length 42 that has the new column names. I then try to rename my columns by using the list:

我有一个包含 44 列的数据框 (df),我想重命名 2:44 列。我有一个长度为 42 的列表 (namesList),其中包含新的列名。然后我尝试使用列表重命名我的列:

df.columns[2:len(df.columns)] = namesList

However I get the error:

但是我收到错误:

TypeError: Index does not support mutable operations

类型错误:索引不支持可变操作

Why do I get this error?

为什么会出现此错误?

回答by jezrael

You need generate new columns names - first and second value from old one and another from list:

您需要生成新的列名称 - 第一个和第二个值来自旧的,另一个来自list

df.columns = df.columns[:2].tolist() + namesList

Sample:

样本:

df = pd.DataFrame({'A':[1,2,3],
                   'B':[4,5,6],
                   'C':[7,8,9],
                   'D':[1,3,5],
                   'E':[5,3,6],
                   'F':[7,4,3]})

print (df)
  A  B  C  D  E  F
0  1  4  7  1  5  7
1  2  5  8  3  3  4
2  3  6  9  5  6  3

namesList = ['K','L','M','N']
df.columns = df.columns[:2].tolist() + namesList
print (df)
   A  B  K  L  M  N
0  1  4  7  1  5  7
1  2  5  8  3  3  4
2  3  6  9  5  6  3