从列表中更改 Pandas Dataframe 中的列名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45468630/
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 04:09:42  来源:igfitidea点击:

Change column names in Pandas Dataframe from a list

pythonpandas

提问by Suresh Raja

Is is possible to change Column Names using data in a list?

是否可以使用列表中的数据更改列名?

df = pd.DataFrame([[1, 1.0, 2.3,0.2,0.53], [2, 3.35, 2.0,0.2,0.65], [2,3.4, 
       2.0,0.25,0.55], [3,3.4,2.0,0.25,0.55], [1,3.4,2.0,0.25,0.55], 
       [3,3.4,2.0,0.25,0.55]], 
       columns=["ID", "A", "B","C","D"])\
       .set_index('ID')

I have my new labels as below:

我的新标签如下:

New_Labels=['NaU', 'MgU', 'AlU', 'SiU']

Is possible to change the names using data in the above list? My original data set has 100 columns and I did not want to do it manually for each column.

是否可以使用上述列表中的数据更改名称?我的原始数据集有 100 列,我不想为每一列手动进行。

I was trying the following using df.rename but keep getting errors. Thanks!

我正在尝试使用 df.rename 进行以下操作,但一直出现错误。谢谢!

回答by Spandan Brahmbhatt

You can use this :

你可以使用这个:

df.columns = New_Labels

回答by jacoblaw

df = pd.DataFrame([[1, 1.0, 2.3,0.2,0.53], [2, 3.35, 2.0,0.2,0.65], [2,3.4, 
       2.0,0.25,0.55], [3,3.4,2.0,0.25,0.55], [1,3.4,2.0,0.25,0.55], 
       [3,3.4,2.0,0.25,0.55]], 
       columns=["ID", "A", "B","C","D"])\
       .set_index('ID')
New_Labels=['NaU', 'MgU', 'AlU', 'SiU']
df.columns = New_Labels

this will make dflook like this:

这将df看起来像这样:

     NaU  MgU   AlU   SiU
ID                       
1   1.00  2.3  0.20  0.53
2   3.35  2.0  0.20  0.65
2   3.40  2.0  0.25  0.55
3   3.40  2.0  0.25  0.55
1   3.40  2.0  0.25  0.55
3   3.40  2.0  0.25  0.55

回答by 5agado

Using renameis a formally more correct approach. You just have to provide a dictionary that maps your current columns names to the new ones (thing that will guarantee expected results even in case of misplaced columns)

使用重命名是一种形式上更正确的方法。您只需要提供一个字典,将当前列名映射到新列名(即使列错位,也能保证预期结果)

new_names = {'A':'NaU', 'B':'MgU', 'C':'Alu', 'D':'SiU'}
df.rename(index=str, columns=new_names)

Notice you can provide entries for the sole names you want to substitute, the rest will remain the same.

请注意,您可以为要替换的唯一名称提供条目,其余的将保持不变。

回答by Neo

df.columns = New_Labels

Take care of the sequence of new column names.

注意新列名的顺序。