我想从
['$a', '$b', '$c', '$d', '$e']
to
['a', 'b', 'c', 'd', 'e']
我想从
['$a', '$b', '$c', '$d', '$e']
to
['a', 'b', 'c', 'd', 'e']
当前回答
另一种替换原始列标签的方法是从原始列标签中删除不需要的字符(此处为“$”)。
这可以通过在df.columns上运行for循环并将剥离的列附加到df.column来完成。
相反,我们可以通过使用下面的列表理解在一个语句中巧妙地做到这一点:
df.columns = [col.strip('$') for col in df.columns]
(Python中的strip方法会从字符串的开头和结尾剥离给定的字符。)
其他回答
我需要重命名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)
由于您只想删除所有列名中的$符号,因此只需执行以下操作:
df = df.rename(columns=lambda x: x.replace('$', ''))
OR
df.rename(columns=lambda x: x.replace('$', ''), inplace=True)
df.columns = ['a', 'b', 'c', 'd', 'e']
它将按照您提供的顺序用您提供的名称替换现有名称。
假设您的数据集名称为df,df具有。
df = ['$a', '$b', '$c', '$d', '$e']`
所以,要重命名这些,我们只需这样做。
df.columns = ['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)