如何使用列表重命名 pandas 中的列 [英] how to rename columns in pandas using a list

查看:61
本文介绍了如何使用列表重命名 pandas 中的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

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

但是我得到了错误:

TypeError:索引不支持可变操作

TypeError: Index does not support mutable operations

为什么会出现此错误?

推荐答案

您需要生成新的列名-旧值中的第一个和第二个值,而 list 中的另一个值:

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

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

示例:

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

这篇关于如何使用列表重命名 pandas 中的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆