我想从

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

to

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

当前回答

我需要重命名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)

其他回答

如“使用文本数据:

df.columns = df.columns.str.replace('$', '')

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

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)

Pandas 0.21+答案

0.21版中的列重命名有一些重要更新。

重命名方法添加了可以设置为columns或1的axis参数。此更新使此方法与panda API的其余部分相匹配。它仍然具有索引和列参数,但不再强制您使用它们。intlace设置为False的set_axis方法允许您使用列表重命名所有索引或列标签。

Pandas 0.21示例+

构造示例DataFrame:

df = pd.DataFrame({'$a':[1,2], '$b': [3,4], 
                   '$c':[5,6], '$d':[7,8], 
                   '$e':[9,10]})

   $a  $b  $c  $d  $e
0   1   3   5   7   9
1   2   4   6   8  10

使用axis='columns'或axis=1的重命名

df.rename({'$a':'a', '$b':'b', '$c':'c', '$d':'d', '$e':'e'}, axis='columns')

or

df.rename({'$a':'a', '$b':'b', '$c':'c', '$d':'d', '$e':'e'}, axis=1)

两者都会导致以下结果:

   a  b  c  d   e
0  1  3  5  7   9
1  2  4  6  8  10

仍然可以使用旧方法签名:

df.rename(columns={'$a':'a', '$b':'b', '$c':'c', '$d':'d', '$e':'e'})

重命名函数还接受将应用于每个列名的函数。

df.rename(lambda x: x[1:], axis='columns')

or

df.rename(lambda x: x[1:], axis=1)

将set_axis与列表一起使用,inplace=False

可以为set_axis方法提供一个长度等于列数(或索引)的列表。目前,inplace默认为True,但在未来的版本中,inplace将默认为False。

df.set_axis(['a', 'b', 'c', 'd', 'e'], axis='columns', inplace=False)

or

df.set_axis(['a', 'b', 'c', 'd', 'e'], axis=1, inplace=False)

为什么不使用df.columns=[‘a’,‘b’,‘c’,‘d’,‘e’]?

像这样直接分配列没有错。这是一个非常好的解决方案。

使用set_axis的优点是它可以作为方法链的一部分使用,并返回DataFrame的新副本。如果没有它,在重新分配列之前,必须将链的中间步骤存储到另一个变量。

# new for pandas 0.21+
df.some_method1()
  .some_method2()
  .set_axis()
  .some_method3()

# old way
df1 = df.some_method1()
        .some_method2()
df1.columns = columns
df1.some_method3()

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

df.columns = pd.Series(df.columns.str.replace("$", ""))
# This way it will work
import pandas as pd

# Define a dictionary 
rankings = {'test': ['a'],
        'odi': ['E'],
        't20': ['P']}

# Convert the dictionary into DataFrame
rankings_pd = pd.DataFrame(rankings)

# Before renaming the columns
print(rankings_pd)

rankings_pd.rename(columns = {'test':'TEST'}, inplace = True)