我想从
['$a', '$b', '$c', '$d', '$e']
to
['a', 'b', 'c', 'd', 'e']
我想从
['$a', '$b', '$c', '$d', '$e']
to
['a', 'b', 'c', 'd', 'e']
当前回答
重命名方法可以采用一个函数,例如:
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)
其他回答
由于您只想删除所有列名中的$符号,因此只需执行以下操作:
df = df.rename(columns=lambda x: x.replace('$', ''))
OR
df.rename(columns=lambda x: x.replace('$', ''), 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()
只需将其分配给.columns属性:
>>> df = pd.DataFrame({'$a':[1,2], '$b': [10,20]})
>>> df
$a $b
0 1 10
1 2 20
>>> df.columns = ['a', 'b']
>>> df
a b
0 1 10
1 2 20
这真的很简单。只需使用:
df.columns = ['Name1', 'Name2', 'Name3'...]
它将按照您输入的顺序分配列名。
如果您必须处理由提供系统命名的超出您控制范围的列负载,我提出了以下方法,它是一种通用方法和特定替换方法的组合。
首先使用正则表达式从数据帧列名创建一个字典,以便丢弃列名的某些附加部分,然后向字典中添加特定替换项,以命名接收数据库中的核心列。
然后将其一次性应用于数据帧。
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)