简体   繁体   English

动态重命名 Python 中的列名

[英]Dynamically rename column names in Python

I am working on a task where I receive several excel files containing similar information.我正在处理一个任务,我收到几个包含类似信息的 excel 文件。 However, every excel sheet has its own column name naming convention, and I have to change the column names in excel manually.但是,每个 excel 表都有自己的列名命名约定,我必须手动更改 excel 中的列名。 Additionally, the columns might get shuffled in the next iteration.此外,列可能会在下一次迭代中被打乱。 So basically, there is no fixed format of the source files currently in place.所以基本上,目前没有固定的源文件格式。

Is there any way for automation with Python?有什么方法可以通过 Python 实现自动化吗?

With pandas, I can rename column names with a loop checking with if condition.使用 pandas,我可以使用 if 条件进行循环检查来重命名列名。 But again, it's hardcoding.但同样,它是硬编码。 How can this be dynamically handled?如何动态处理?

for i in range(len(df)):
   # print(col_names[i])
    if df[i] == 'Department':
        df[i] = 'dept'

Use the .rename method:使用.rename方法:

df.rename({'old_col_name':'new_col_name','old_col_name2':'new_col_name2'},axis=1

You can use .rename method:您可以使用.rename方法:

df.rename(columns={'oldName1': 'newName1', 'oldName2': 'newName2'}, inplace=True)

If your column indexes remain same, you can also do:如果您的列索引保持不变,您还可以执行以下操作:

df.columns = ['newName1', 'newName2']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM