我想从

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

to

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

当前回答

假设您可以使用正则表达式,则此解决方案无需使用正则表达式进行手动编码:

import pandas as pd
import re

srch = re.compile(r"\w+")

data = pd.read_csv("CSV_FILE.csv")
cols = data.columns
new_cols = list(map(lambda v:v.group(), (list(map(srch.search, cols)))))
data.columns = new_cols

其他回答

如果您必须处理由提供系统命名的超出您控制范围的列负载,我提出了以下方法,它是一种通用方法和特定替换方法的组合。

首先使用正则表达式从数据帧列名创建一个字典,以便丢弃列名的某些附加部分,然后向字典中添加特定替换项,以命名接收数据库中的核心列。

然后将其一次性应用于数据帧。

dict = dict(zip(df.columns, df.columns.str.replace('(:S$|:C1$|:L$|:D$|\.Serial:L$)', '')))
dict['brand_timeseries:C1'] = 'BTS'
dict['respid:L'] = 'RespID'
dict['country:C1'] = 'CountryID'
dict['pim1:D'] = 'pim_actual'
df.rename(columns=dict, inplace=True)

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

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

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

列名与系列名称

我想解释一下幕后发生的事情。

数据帧是一组系列。

序列又是numpy.array的扩展。

numpy.arrays具有属性.name。

这是系列的名称。熊猫很少尊重这个属性,但它会在某些地方停留,可以用来攻击熊猫的一些行为。

命名列列表

这里有很多答案谈到df.columns属性是一个列表,而实际上它是一个系列。这意味着它具有.name属性。

如果您决定填写列的名称“系列:

df.columns = ['column_one', 'column_two']
df.columns.names = ['name of the list of columns']
df.index.names = ['name of the index']

name of the list of columns     column_one  column_two
name of the index
0                                    4           1
1                                    5           2
2                                    6           3

请注意,索引的名称总是低一列。

挥之不去的艺术事实

.name属性有时会持续存在。如果将df.columns设置为['one','two'],则df.one.name将为'one'。

如果您将df.one.name设置为'three',则df.columns仍然会给您['one','two'],df.one.name会给您'three]。

BUT

pd.DataFrame(df.one)将返回

    three
0       1
1       2
2       3

因为Pandas重用已经定义的Series的.name。

多级列名

Pandas有多种方法来实现多层列名。这里面没有太多魔法,但我想在我的回答中也包括这一点,因为我没有看到任何人在这里学习这一点。

    |one            |
    |one      |two  |
0   |  4      |  1  |
1   |  5      |  2  |
2   |  6      |  3  |

通过将列设置为列表,这很容易实现,如下所示:

df.columns = [['one', 'one'], ['one', 'two']]