gpt4 book ai didi

python - 在 Pandas 中重命名列名

转载 作者:bug小助手 更新时间:2023-10-28 01:28:31 26 4
gpt4 key购买 nike

我想更改 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=1inplace=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

关于python - 在 Pandas 中重命名列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11346283/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com