
在平时的开发需求中,涉及到更换字段列名的操作,我们可以使用.rename方法进行实现该需求
以下提供了两个练习案例进行复盘与学习,方便日后进行查阅
练习案例1
import pandas as pd
df = pd.DataFrame([['L123','A',0,123],
['L456','A',1,456],
['L437','C',0,789],
['L112','B',1,741],
['L211','A',0,852],
['L985','B',1,963]
],columns=['Raw Material','Level','Passing','l/t'])
# 更改'Raw Material'和'l/t'两个栏位的名称
df = df.rename(columns = {'Raw Material':'Material','l/t':'LT'})
df
df(处理后)
练习案例2
import pandas as pd
cal_supply = pd.DataFrame([['L123',1,2,3],
['L456',4,5,6],
['L437',7,8,9],
['L112',10,11,12],
['L211',13,14,15],
['L985',16,17,18]
],columns=['Material','W1|6/22','W2|6/23','W3|6/24'])
# 更换cal_supply表中的W1-W3的列名
new_dict = {
key:key.split('|')[1]
for i, key in enumerate(cal_supply.columns.tolist()[1:])
}
cal_supply.rename(columns=new_dict, inplace=True)
cal_supply
new_dict
cal_supply(处理后)
扩展补充
更换字段栏位名称还可使用直接赋值的方式
import pandas as pd
df = pd.DataFrame([['FOL','A',0,123],
['FOL','A',1,456],
['FOL','C',0,789],
['FJZ','B',1,741],
['FJZ','A',0,852],
['FJZ','B',1,963]
],columns=['Site','Level','Passing','l/t'])
new_columns = ['Site','Type','Passing','LT']
# 替换列名:更换字段'Level'和'l/t'名称
df.columns = new_columns
df
处理后的df