问题描述
是否可以使用列表中的数据更改列名?
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')
我的新标签如下:
New_Labels=['NaU', 'MgU', 'AlU', 'SiU']
是否可以使用以上列表中的数据更改名称?我的原始数据集有100列,而我不想为每一列手动进行操作.
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.
我正在尝试使用df.rename进行以下操作,但始终出现错误.谢谢!
I was trying the following using df.rename but keep getting errors. Thanks!
推荐答案
使用重命名是形式上更正确的方法.您只需要提供一个字典即可将您当前的列名映射到新的列(即使在列放错的情况下也可以保证预期的结果)
Using rename is 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.
这篇关于从列表中更改Pandas Dataframe中的列名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!