[英]How to rename a column which have a same name with another one
I have an data - frame as below... 我有一个数据框架如下...
AA BB CC DD EE ... LL MM NN NN
0 a0 b0 c0 d0 e0 ... l0 m0 x0 y0
1 a1 b1 c1 d1 e1 ... l1 m1 x1 y1
2 a2 b2 c2 d2 e2 ... l2 m2 x2 y2
3 a3 b3 c3 d3 e3 ... l3 m3 x3 y3
I would like to change the name of 'NN' which is in right edge. 我想更改右边缘的'NN'的名称。
Somebody says you should use dataframe.columns = [AA,BB,CC...,NN,ZZ]
. 有人说你应该使用dataframe.columns = [AA,BB,CC...,NN,ZZ]
。
However, in my case, number of columns is too many to use this method. 但是,就我而言,列数太多而无法使用此方法。
I have tried as below... 我试过如下......
dataframe.columns[-1] = 'ZZ'
However, I just have got the script 但是,我只是得到了脚本
TypeError: Index does not support mutable operations. TypeError:Index不支持可变操作。
You can slice all column names without last, create new list
with tolist
, add new name ['ZZ']
and reassign back to df.columns
: 您可以在不使用last的情况下对所有列名称进行切片,使用tolist
创建新list
,添加新名称['ZZ']
并重新分配给df.columns
:
df.columns = df.columns[:-1].tolist() + ['ZZ']
print (df)
AA BB CC DD EE ... LL MM NN ZZ
0 a0 b0 c0 d0 e0 ... l0 m0 x0 y0
1 a1 b1 c1 d1 e1 ... l1 m1 x1 y1
2 a2 b2 c2 d2 e2 ... l2 m2 x2 y2
3 a3 b3 c3 d3 e3 ... l3 m3 x3 y3
Copy the columns to a new list, modify the last index of the list, and reassign back to df.columns
: 将列复制到新列表,修改列表的最后一个索引,然后重新分配给df.columns
:
>>> col = list(df.columns)
>>> col
['z', 'z']
>>> col[-1] = 'ZZ'
>>> df.columns = col
>>> df
z ZZ
0 1 10
1 2 20
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.