我想从

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

to

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

当前回答

我的方法是通用的,您可以通过逗号分隔分隔符=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.columns上运行for循环并将剥离的列附加到df.column来完成。

相反,我们可以通过使用下面的列表理解在一个语句中巧妙地做到这一点:

df.columns = [col.strip('$') for col in df.columns]

(Python中的strip方法会从字符串的开头和结尾剥离给定的字符。)

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。当您只需要重命名几个列来纠正拼写错误、重音、删除特殊字符等时,它非常有用。

除了已经提供的解决方案之外,您还可以在读取文件时替换所有列。我们可以使用names和header=0来实现这一点。

首先,我们创建一个我们喜欢用作列名的名称列表:

import pandas as pd

ufo_cols = ['city', 'color reported', 'shape reported', 'state', 'time']
ufo.columns = ufo_cols

ufo = pd.read_csv('link to the file you are using', names = ufo_cols, header = 0)

在这种情况下,所有列名都将替换为列表中的名称。

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

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

可以将lstrip或strip方法与索引一起使用:

df.columns = df.columns.str.lstrip('$')

or

cols = ['$a', '$b', '$c', '$d', '$e']
pd.Series(cols).str.lstrip('$').tolist()

输出:

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