我想从
['$a', '$b', '$c', '$d', '$e']
to
['a', 'b', 'c', 'd', 'e']
我想从
['$a', '$b', '$c', '$d', '$e']
to
['a', 'b', 'c', 'd', 'e']
当前回答
由于您只想删除所有列名中的$符号,因此只需执行以下操作:
df = df.rename(columns=lambda x: x.replace('$', ''))
OR
df.rename(columns=lambda x: x.replace('$', ''), inplace=True)
其他回答
如“使用文本数据:
df.columns = df.columns.str.replace('$', '')
另一个选项是使用正则表达式重命名:
import pandas as pd
import re
df = pd.DataFrame({'$a':[1,2], '$b':[3,4], '$c':[5,6]})
df = df.rename(columns=lambda x: re.sub('\$','',x))
>>> df
a b c
0 1 3 5
1 2 4 6
另一种替换原始列标签的方法是从原始列标签中删除不需要的字符(此处为“$”)。
这可以通过在df.columns上运行for循环并将剥离的列附加到df.column来完成。
相反,我们可以通过使用下面的列表理解在一个语句中巧妙地做到这一点:
df.columns = [col.strip('$') for col in df.columns]
(Python中的strip方法会从字符串的开头和结尾剥离给定的字符。)
假设您的数据集名称为df,df具有。
df = ['$a', '$b', '$c', '$d', '$e']`
所以,要重命名这些,我们只需这样做。
df.columns = ['a','b','c','d','e']
# This way it will work
import pandas as pd
# Define a dictionary
rankings = {'test': ['a'],
'odi': ['E'],
't20': ['P']}
# Convert the dictionary into DataFrame
rankings_pd = pd.DataFrame(rankings)
# Before renaming the columns
print(rankings_pd)
rankings_pd.rename(columns = {'test':'TEST'}, inplace = True)