我想从
['$a', '$b', '$c', '$d', '$e']
to
['a', 'b', 'c', 'd', 'e']
我想从
['$a', '$b', '$c', '$d', '$e']
to
['a', 'b', 'c', 'd', 'e']
当前回答
您可以使用str.slice:
df.columns = df.columns.str.slice(1)
其他回答
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]
如果您必须处理由提供系统命名的超出您控制范围的列负载,我提出了以下方法,它是一种通用方法和特定替换方法的组合。
首先使用正则表达式从数据帧列名创建一个字典,以便丢弃列名的某些附加部分,然后向字典中添加特定替换项,以命名接收数据库中的核心列。
然后将其一次性应用于数据帧。
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)
我需要重命名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)
您可以使用str.slice:
df.columns = df.columns.str.slice(1)
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()