简体   繁体   English

如何重命名与另一个具有相同名称的列

[英]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.

相关问题 如何为在另一列 pandas 中具有相同值的那些行使一列的值相同 - How to make same value of one column for those rows which have same values in another column pandas Python:我有具有相同列名的 Pandas 数据框。 如何更改其中之一? - Python: I have pandas dataframe which has the same column name. How to change one of those? 如何重命名 python 中包含相同名称的子文件夹 - How to rename subfolders which contain same name in python 如何重命名一个类似于名称的数字的数据框列? - how to rename a dataframe column which is a digit like name? 如果它们在列中具有相同的值并且其中至少一个包含另一列中的字符串,如何保留多行 - How to keep multiple rows if they have the same value within a column AND at least one of them contains a string in another column 如何进行查询以过滤其中一列等于同一表的另一列的行? - How to make a query that filters rows in which one column equals another one of the same table? 如何在 y 轴上绘制一列(名称)并在同一 y 轴上绘制另一列的值 - How to subplot one column (name) on y-axis and in the same y-axis another column with values 两个pip安装的模块同名,select怎么加载哪一个? - Two pip-installed modules have the same name, how to select which one is loaded? 如何按列名过滤值,然后将具有相同值的行提取到另一个CSV文件? Python /熊猫 - How to filter values by Column Name and then extract the rows that have the same value to another CSV file? Python/Pandas 如何重命名,熊猫中没有列名? - How to rename, No column name in pandas?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM