我想从

['$a', '$b', '$c', '$d', '$e']

to

['a', 'b', 'c', 'd', 'e']

当前回答

如果您只想删除“$”符号,请使用以下代码

df.columns = pd.Series(df.columns.str.replace("$", ""))

其他回答

df.columns = ['a', 'b', 'c', 'd', 'e']

它将按照您提供的顺序用您提供的名称替换现有名称。

重命名特定列

使用df.reame()函数并引用要重命名的列。并非所有列都必须重命名:

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()文档。


重新分配列标题

使用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

一个简单而“有趣”(和蟒蛇?)的解决方案:

df.rename(columns={x: x.replace('$', '') for x in df.columns})

哪里:

df = pd.DataFrame(columns=['$a', '$b', '$c', '$d', '$e'])

步骤:

获取DataFrame的列作为列表:

df.columns

在DataFrames中重命名的方法:

df.rename()

属性以指定要重命名列:

columns={}

在字典中,您需要指定要重命名的列(在每个键中)以及它们将获得的新名称(每个值)

{'old_col_name': 'new_col_name', ...}

由于您的更改遵循一种模式,为了删除每列中的$字符,我们可以使用字典理解:

{x: x.replace('$', '') for x in df.columns}

如果已经有新列名的列表,可以尝试以下操作:

new_cols = ['a', 'b', 'c', 'd', 'e']
new_names_map = {df.columns[i]:new_cols[i] for i in range(len(new_cols))}

df.rename(new_names_map, axis=1, inplace=True)

我需要重命名XGBoost的功能,但它不喜欢这些功能:

import re
regex = r"[!\"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~ ]+"
X_trn.columns = X_trn.columns.str.replace(regex, '_', regex=True)
X_tst.columns = X_tst.columns.str.replace(regex, '_', regex=True)