pandas替换字段名
时间: 2023-11-05 19:59:49 浏览: 108
要替换pandas数据框中的字段名,可以使用两种方法:直接赋值和rename()函数。
直接赋值方法的示例代码如下:
``` python
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
```
rename()函数方法的示例代码如下:
``` python
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'})
```
阅读全文