我想从

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

to

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

当前回答

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

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

其他回答

Use:

old_names = ['$a', '$b', '$c', '$d', '$e'] 
new_names = ['a', 'b', 'c', 'd', 'e']
df.rename(columns=dict(zip(old_names, new_names)), inplace=True)

这样,您可以根据需要手动编辑new_names。当您只需要重命名几个列来纠正拼写错误、重音、删除特殊字符等时,它非常有用。

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

使用映射重命名列: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

这真的很简单。只需使用:

df.columns = ['Name1', 'Name2', 'Name3'...]

它将按照您输入的顺序分配列名。

df.rename(index=str, columns={'A':'a', 'B':'b'})

pandas.DataFrame.rename

df = pd.DataFrame({'$a': [1], '$b': [1], '$c': [1], '$d': [1], '$e': [1]})

如果新列列表的顺序与现有列的顺序相同,则分配很简单:

new_cols = ['a', 'b', 'c', 'd', 'e']
df.columns = new_cols
>>> df
   a  b  c  d  e
0  1  1  1  1  1

如果您有一个将旧列名键入到新列名的字典,可以执行以下操作:

d = {'$a': 'a', '$b': 'b', '$c': 'c', '$d': 'd', '$e': 'e'}
df.columns = df.columns.map(lambda col: d[col])  # Or `.map(d.get)` as pointed out by @PiRSquared.
>>> df
   a  b  c  d  e
0  1  1  1  1  1

如果你没有列表或字典映射,你可以通过列表理解去掉前导$符号:

df.columns = [col[1:] if col[0] == '$' else col for col in df]