我想从

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

to

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

当前回答

让我们通过一个小例子来理解重命名。。。

使用映射重命名列:df=pd.DataFrame({“A”:[1,2,3],“B”:[4,5,6]})#创建列名为A和B的dfdf.reame({“A”:“new_A”,“B”:“new_B”},axis='columns',inplace=True)#用'new_A'重命名列A,用'new_B'重命名列B输出:新a新b0 1 41 2 52 3 6使用映射重命名索引/Row_Name:df.reame({0:“x”,1:“y”,2:“z”},axis='index',inplace=True)#行名称被'x'、'y'和'z'替换。输出:新a新bx 142015年z 3 6

其他回答

重命名Pandas中的列是一项简单的任务。

df.rename(columns={'$a': 'a', '$b': 'b', '$c': 'c', '$d': 'd', '$e': 'e'}, 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)

我的方法是通用的,您可以通过逗号分隔分隔符=variable来添加额外的分隔符,并对其进行未来验证。

工作代码:

import pandas as pd
import re


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

delimiters = '$'
matchPattern = '|'.join(map(re.escape, delimiters))
df.columns = [re.split(matchPattern, i)[1] for i in df.columns ]

输出:

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

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

由于您只想删除所有列名中的$符号,因此只需执行以下操作:

df = df.rename(columns=lambda x: x.replace('$', ''))

OR

df.rename(columns=lambda x: x.replace('$', ''), inplace=True)

重命名方法可以采用一个函数,例如:

In [11]: df.columns
Out[11]: Index([u'$a', u'$b', u'$c', u'$d', u'$e'], dtype=object)

In [12]: df.rename(columns=lambda x: x[1:], inplace=True)

In [13]: df.columns
Out[13]: Index([u'a', u'b', u'c', u'd', u'e'], dtype=object)