我想更改 Pandas DataFrame 的列标签
['$a', '$b', '$c', '$d', '$e']
到
['a', 'b', 'c', 'd', 'e']
重命名特定列
使用 df.rename()
函数并引用要重命名的列。并非所有列都必须重命名:
df = df.rename(columns={'oldName1': 'newName1', 'oldName2': 'newName2'})
# Or rename the existing DataFrame (rather than creating a copy)
df.rename(columns={'oldName1': 'newName1', 'oldName2': 'newName2'}, inplace=True)
最小代码示例
df = pd.DataFrame('x', index=range(3), columns=list('abcde'))
df
a b c d e
0 x x x x x
1 x x x x x
2 x x x x x
以下方法都有效并产生相同的输出:
df2 = df.rename({'a': 'X', 'b': 'Y'}, axis=1) # new method
df2 = df.rename({'a': 'X', 'b': 'Y'}, axis='columns')
df2 = df.rename(columns={'a': 'X', 'b': 'Y'}) # old method
df2
X Y c d e
0 x x x x x
1 x x x x x
2 x x x x x
请记住将结果分配回去,因为修改不是就地的。或者,指定 inplace=True
:
df.rename({'a': 'X', 'b': 'Y'}, axis=1, inplace=True)
df
X Y c d e
0 x x x x x
1 x x x x x
2 x x x x x
从 v0.25 开始,您还可以指定 errors='raise'
以在指定要重命名的列无效时引发错误。见 v0.25 rename()
docs .
重新分配列标题
使用 df.set_axis()
使用 axis=1
和 inplace=False
(返回副本)。
df2 = df.set_axis(['V', 'W', 'X', 'Y', 'Z'], axis=1, inplace=False)
df2
V W X Y Z
0 x x x x x
1 x x x x x
2 x x x x x
这会返回一个副本,但您可以通过设置 inplace=True
就地修改 DataFrame(这是 <=0.24 版本的默认行为,但将来可能会更改)。
您也可以直接分配标题:
df.columns = ['V', 'W', 'X', 'Y', 'Z']
df
V W X Y Z
0 x x x x x
1 x x x x x
2 x x x x x
我是一名优秀的程序员,十分优秀!